package com.edais.service.imp;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.edais.dao.*;
import com.edais.domain.*;
import com.edais.persistence.UserMapper;
import com.edais.persistence.UserMessageMapper;
import com.edais.service.*;
import com.edais.util.*;
import com.edais.util.RSAThirdParty.RSA;
import com.edais.util.sina.ThridPartyFunctionUtil;
import com.edais.vo.UserBankCardVo;
import com.umpay.api.util.StringUtil;
import com.yunzhi.domain.RequestHeader;
import com.yunzhi.domain.ResultCode;
import com.yunzhi.domain.ResultConstant;
import com.yunzhi.domain.ResultDTO;
import com.yunzhi.util.TokenUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.net.ftp.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.imageio.stream.ImageOutputStream;
import javax.servlet.http.HttpServletRequest;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;

@Service

// @Transactional
public class UserServiceImp implements UserService {
	private static final Log logger = LogFactory.getLog(UserServiceImp.class);

	@Autowired
	private UserDao usersDao;

	@Autowired
	private CaptchaDao captchaDao;

	@Autowired
	private SecurityDao securityDao;

	@Autowired
	private CenterService centerService;

	@Autowired
	private OptionDao optionDao;

	@Autowired
	private ActivityDao activityDao;

	@Autowired
	private UserAuthenticationDao userAuthenticationDao;

	@Autowired
	private SMSService sMSService;

	@Autowired
	private RateRisesCouponsDao rateRisesCouponsDao;

	@Autowired
	private UserCardDao userCardDao;

	@Autowired
	private ErrorMessageService errorMessageService;

	@Autowired
	private ThirdProductRouteDao thirdProductRouteDao;

	@Autowired
	private UserMessageMapper userMessageMapper;

	@Autowired
	private ActivityService activityService;

	@Autowired
	private SystemSettingDao systemSettingDao;

	@Autowired
	private ConfigSmsDao configSmsDao;

	@Autowired
	private FastDFSUtil fastDFSUtil;

	@Autowired
	private UserMapper userMapper;

	@Override
	public List<GetUserInfo> loginCheck(String mobile, String password, String type) throws Exception {
		return usersDao.loginCheck(mobile, password, type);
	}

	@Override
	@Transactional
	public void resetPsw(String mobile, String newPsw, String type) throws Exception {
		// TODO Auto-generated method stub
		this.usersDao.resetPsw(mobile, newPsw, type);
	}

	@Override
	@Transactional
	public void resetPswCash(String mobile, String newPsw, String type) throws Exception {
		// TODO Auto-generated method stub
		this.usersDao.resetPswCash(mobile, newPsw, type);
	}

	@Override
	public User getUserDetail(String userID) throws Exception {
		// TODO Auto-generated method stub
		return usersDao.getUserDetail(userID);
	}

	@Override
	public UserAccountDetail getUserAccountDetail(String userID) throws Exception {
		// TODO Auto-generated method stub
		return usersDao.getUserAccountDetail(userID);
	}

	@Override
	@Transactional
	public void resetPswById(String newPsw, String userID, String oldPsw) throws Exception {
		this.usersDao.resetPswById(newPsw, userID, oldPsw);
	}

	@Override
	public UserInfo getUserInfo(String userId) throws Exception {
		// TODO Auto-generated method stub
		return this.usersDao.getUserInfo(userId);
	}

	@Override
	@Transactional
	public void saveRandomCode(String mobileNum, String randomCode, String type) throws Exception {
		// TODO Auto-generated method stub
		Date now = new Date();
		Date lostTime = new Date(now.getTime() + 600000);// 10分钟后的时间

		MobileValidate mobileValidate = new MobileValidate();
		mobileValidate.setCreate_time(now);
		mobileValidate.setEnable('Y');
		mobileValidate.setLost_time(lostTime);
		mobileValidate.setMobile(mobileNum);
		mobileValidate.setRandom_char(randomCode);
		mobileValidate.setValidate_char(randomCode);
		mobileValidate.setValidate_type(type);

		this.usersDao.saveRandomCode(mobileValidate);
	}

	@Override
	@Transactional
	public void updateToBeLender(String allowLend, String userId) throws Exception {
		this.usersDao.updateToBeLender(allowLend, userId);

	}

	@Override
	public int getUserNotMeByInviteCode(String invitationCode, String id) throws Exception {
		return this.usersDao.getUserNotMeByInviteCode(invitationCode, id);
	}

	/**
	 * 查询邀请码在用户表中的个数
	 */
	@Override
	public int getInviteCodeCount(String invitationCode) throws Exception {
		// TODO Auto-generated method stub
		return this.usersDao.getInviteCodeCount(invitationCode);
	}

	/**
	 * 更新用户绑定的邀请码
	 */
	@Override
	@Transactional
	public void updateInvitationCode(String invitationCode, String userId) throws Exception {
		this.usersDao.updateInvitationCode(invitationCode.toUpperCase(), userId);
	}

	/**
	 * 获取用户当前绑定手机号
	 */
	@Override
	public Map<String, Object> getUserMobile(String userId) throws Exception {
		Map<String, Object> rtnMap = new HashMap<String, Object>();
		String mobile = this.captchaDao.getMobileById(userId);
		if (StringUtil.isEmpty(mobile)) {
			rtnMap.put("rescode", Consts.CHECK_CODE);
			rtnMap.put("resmsg", Consts.ErrorMsg.MSG00028); // 用户未绑定手机号
			rtnMap.put("resmsg_cn", Message.CnDescriptionExpression.MOBILE_IS_NONBOUND);
			return rtnMap;
		}

		rtnMap.put("mobile", mobile);
		rtnMap.put("rescode", Consts.SUCCESS_CODE);
		rtnMap.put("resmsg", Consts.SUCCESS_DESCRIBE);
		rtnMap.put("resmsg_cn", "");

		return rtnMap;
	}

	/**
	 * 根据邀请码获取邀请人信息
	 */
	@Override
	@Transactional
	public User getInviterInfo(String invitationCode) throws Exception {
		return usersDao.getInviterInfo(invitationCode);
	}

	/**
	 * 获得ftp配置信息，从参数配置表里面
	 * 
	 * @return
	 * @throws Exception
	 */
	public Map<String, String> getSetting() throws Exception {
		Map<String, String> systemSettingMap = new HashMap<String, String>();
		/** 测试参数 */
		// //ftp的地址、用户名、密码
		// map.put("ftpUrl1", "172.17.34.102");
		// map.put("ftpUrl1_userLogin", "androidTest");
		// map.put("ftpUrl1_password", "123456");
		// // 头像路径
		// map.put("ftpHeadImage_path", "/home/weblogic/war/edaiMobile/head/");
		// // 移动mobile访问路径
		// map.put("mobile_visit_Ip", "http://172.17.34.102:7007");

		/** 数据库参数 */
		// ftp的地址、用户名、密码
		String ftpUrl1 = usersDao.getSystemSettingValue(Consts.SystemSettingUpload.UPLOAD_FTPURL);
		String ftpUrl1_userLogin = usersDao.getSystemSettingValue(Consts.SystemSettingUpload.UPLOAD_FTPURL_USERLOGIN);
		String ftpUrl1_password = usersDao.getSystemSettingValue(Consts.SystemSettingUpload.UPLOAD_FTPURL_PASSWORD);
		// 头像路径 (原图)
		String ftpHeadImage_path = usersDao.getSystemSettingValue(Consts.SystemSettingUpload.UPLOAD_HEAD_IMAGE_PATH);
		// 头像路径 (缩略图)
		String ftpDisposeImage_path = usersDao
				.getSystemSettingValue(Consts.SystemSettingUpload.UPLOAD_DISPOSE_IMAGE_PATH);
		// 移动mobile访问路径
		String mobile_visit_Ip = usersDao.getSystemSettingValue(Consts.SystemSettingUpload.UPLOAD_MOBILE_VISIT_IP);
		// ftp的地址、用户名、密码
		systemSettingMap.put("ftpUrl1", ftpUrl1);
		systemSettingMap.put("ftpUrl1_userLogin", ftpUrl1_userLogin);
		systemSettingMap.put("ftpUrl1_password", ftpUrl1_password);
		// 头像路径 (原图)
		systemSettingMap.put("ftpHeadImage_path", ftpHeadImage_path);
		// 头像路径 (缩略图)
		systemSettingMap.put("ftpDisposeImage_path", ftpDisposeImage_path);
		// 移动mobile访问路径
		systemSettingMap.put("mobile_visit_Ip", mobile_visit_Ip);

		/** 数据库参数 */
		System.out.println(systemSettingMap);
		return systemSettingMap;
	}

	/**
	 * 更改头像
	 */
	@Override
	@Transactional
	public Map<String, Object> modifySculpture(MultipartFile imageFile,String userId,String logInfo) throws Exception {

		logger.info(logInfo+"上传图像开始");

		Map<String, Object> mapResult = new HashMap();

		//1.上传源图
		Calendar calendar = Calendar.getInstance();
		//新上传源图片名称
		String newOriginalfileName = StrUtil.fileNameMD5(userId + String.valueOf(calendar.getTimeInMillis()))+ RandomUtil.radomCode(3)+imageFile.getOriginalFilename().substring(imageFile.getOriginalFilename().indexOf("."));
		//新上传缩略图片名称
		String newDisposefileName = StrUtil.fileNameMD5(userId + String.valueOf(calendar.getTimeInMillis()))+RandomUtil.radomCode(3)+imageFile.getOriginalFilename().substring(imageFile.getOriginalFilename().indexOf("."));

		String ftpPathOriginal=fastDFSUtil.uploadPic(imageFile.getBytes(),newOriginalfileName,imageFile.getSize());

		//2.上传缩略图
		// 读入源图像
		InputStream inputStreamTemp =imageFile.getInputStream();// 文件
		BufferedImage bufferedImage = ImageIO.read(inputStreamTemp);
		ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
		// 获取一个宽、长是原来scale的图像实例
		Image image = bufferedImage.getScaledInstance(120, 120, java.awt.Image.SCALE_SMOOTH);
		// 缩放图像
		BufferedImage tag = new BufferedImage(120, 120, BufferedImage.TYPE_INT_RGB);

		Graphics2D graphics = (Graphics2D) tag.getGraphics();

		graphics.drawImage(image, 0, 0, null); // 绘制缩小后的图
		image.flush();
		ImageOutputStream imageOutputStream = ImageIO.createImageOutputStream(byteArrayOutputStream);
		ImageIO.write(tag, "jpg", imageOutputStream);
		InputStream inputStreamDispose = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());

		byte[] fileBuff = fastDFSUtil.getFileBuffer(inputStreamDispose, byteArrayOutputStream.size());
		String ftpPathDispose=fastDFSUtil.uploadPic(fileBuff,newDisposefileName,byteArrayOutputStream.size());
		//用户头像访问根目录
		String uploadBasePath=activityService.findParamValueByName("upload_userimg_serves_basepath");

		// 返回结果
		if(StringUtils.isNotBlank(ftpPathOriginal)){
			ftpPathOriginal=uploadBasePath+ftpPathOriginal;
		}

		if(StringUtils.isNotBlank(ftpPathDispose)){
			ftpPathDispose=uploadBasePath+ftpPathDispose;
		}

		mapResult.put("ftpPathOriginal", ftpPathOriginal);
		mapResult.put("ftpPathDispose", ftpPathDispose);
		mapResult.put("userId",userId);
		logger.info(logInfo+"返回上传原始图片地址："+ftpPathOriginal);
		logger.info(logInfo+"返回上传缩略图片地址："+ftpPathDispose);
		// 修改数据库
		this.usersDao.modifySculpture(mapResult);
		logger.info(logInfo+"上传图像结束");
		return mapResult;
	}

	/**
	 * 登录处理
	 */
	@Override
	@Transactional
	public void doLogin(Map<String, String> map) throws Exception {

	}

	@Override
	public int checkIdCardIsExist(Map<String, Object> map) throws Exception {
		// TODO Auto-generated method stub
		return usersDao.checkIdCardIsExist(map);
	}

	/**
	 * guanxuxing 短信推送
	 */
	@Override
	public String sendSmsW(HttpServletRequest request, Map<String, String> pMap) throws Exception {
		String mobileNum = pMap.get("phoneNum");
		// (手机)短信系统 工具
		// 发送短信
		String conent = pMap.get("content");
		// 第三方工程请求url
		String url = ThirdPartyEnvUtil.getValue("smsUrl");
		// 请求参数封装
		Map<String, String> paramMap = new HashMap<String, String>();
		paramMap.put("content", conent);
		paramMap.put("mobileListParams", mobileNum);
		String requestParam = "keyRandom=KEY_RANDOM";
		String publicKeyParam = "";
		try {
			publicKeyParam = RSA.getPublick_Key_Encrypt(paramMap);
			requestParam = requestParam.replace("KEY_RANDOM", URLEncoder.encode(publicKeyParam, "utf-8"));
		} catch (Exception e) {
			logger.error("公钥加密串：" + e);
			logger.error("发送短信失败!");
			throw new RuntimeException("短信发送失败！");
		}
		// 发送短信消息
		String smsResult = CommonUtil.sendPostByHttp(url, requestParam);
		if (StringUtils.isBlank(smsResult)) {
			logger.error("发送短信失败!");
			throw new RuntimeException("短信发送失败！");
		} else {
			// 解析发送结果
			Map smsResultMap = JsonUtil.getMapFromJsonString(smsResult);
			if (null == smsResultMap || "sysException".equals(smsResultMap.get("rescode"))) {
				logger.error("发送短信失败：" + smsResultMap.get("resmsg_cn"));
				throw new RuntimeException("短信发送失败！！");
			} else if ("BusinessException".equals(smsResultMap.get("rescode"))) {
				// 业务异常
				logger.error("发送短信失败：" + smsResultMap.get("resmsg_cn"));
				throw new RuntimeException("短信发送失败！！");
			}
		}

		// 处理返回结果
		String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(), Consts.SUCCESS_CODE,
				Consts.SUCCESS_DESCRIBE, "");
		return result;
	}

	/**
	 * 手机是否存在检查
	 */
	@Override
	public int phoneIsExisted(String mobile) throws Exception {
		return usersDao.phoneIsExisted(mobile);
	}

	/**
	 * 发送验证码主处理
	 */
	@Override
	public ResultDTO getCaptcha(JSONObject map, String infoTime) throws Exception {

		// 查询短信发送记录表
		Map<String, Object> querMap = new HashMap<>();
		querMap.put("userMobile", map.get("userMobile"));
		querMap.put("setupFlag", map.get("setupFlag"));
		Map sendMesRecMap = usersDao.querySendMesRec(querMap);
		String type = map.getString("type");
		String conent = "";
		Map<String, String> resultMap = new HashMap<>();
		// 防止重复发送
		if (null != sendMesRecMap) {
			Date codeTime = (Date) sendMesRecMap.get("END_SETUP_TIME");
			Date codeTime_10;
			if ("REGISTER".equals(type)) {
				// 注册90秒有效
				codeTime_10 = new Date(codeTime.getTime() + 90 * 1 * 1000);// 1.5分钟后的时间
			} else if ("RESETPASSWORD".equals(type)) {
				// 重置登录密码没有时间限制
				codeTime_10 = new Date(codeTime.getTime());// 1分钟后的时间
			} else {
				// 除了注册外其余都是60秒
				codeTime_10 = new Date(codeTime.getTime() + 60 * 1 * 1000);// 1分钟后的时间
			}

			Date now = usersDao.querySysDate();
			if (now.getTime() <= codeTime_10.getTime()) {
				// 不可重复发送
				return new ResultDTO<>(ResultCode.FAILED, Message.CnDescriptionExpression.SMS_BUSY);
			}

			int setupDayResult = Integer.parseInt(String.valueOf(sendMesRecMap.get("SETUP_DAY_RESULT")));// 当日发送次数
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			// 最后发送日期
			String endSetUpDate = sdf.format(codeTime);
			// 数据库当前日期
			String dataDate = sdf.format(now);

			// 如果最后发送时间和数据库当前日期不同:恢复该用户当天发送次数
			if (!endSetUpDate.equalsIgnoreCase(dataDate)) {
				usersDao.updateJudgeCaptchaTime(querMap);
			} else {
				if (setupDayResult >= Integer.parseInt(infoTime)) {
					// 发短信已超过当日限额次数
					return new ResultDTO<>(ResultCode.FAILED, "今日您已获取短信验证码超过" + infoTime + "次");

				}
			}
		}

		// 获取随机验证码:随机产生的6位数字
		// String randomCode = CommonUtil.getRandomCode();
		// ouyy 六位验证码改成四位
		String randomCode = CommonUtil.getRandomCode_Four();
		/*
		 * 验证码类别： 注册验证码(REGISTER), MOBILE_REGISTER:手机注册 登录验证码(WXLOGIN),
		 * 重置登陆密码(FORGET_PASSWORD), FIND_PASSWORD_BY_MOBILE:通过手机找回密码
		 * 解绑手机(MODIFY_MOBILE), MODIFY_BIND_MOBILE:修改绑定手机 绑定手机(BINDING_MOBILE),
		 * MODIFY_BIND_MOBILE:修改绑定手机 MODIFY_PASSWORD:找回登陆密码
		 * MODIFY_PASSWORD:修改注册密码 CASHDRAW:提现
		 */

		// 获取短信模版
		String templateKey = "";
		if ("REGISTER".equals(type)) {
			templateKey = "MOBILE_REGISTER";
		} else if ("FORGET_PASSWORD".equals(type)) {
			templateKey = "FIND_PASSWORD_BY_MOBILE";
		} else if ("MODIFY_MOBILE".equals(type)) {
			templateKey = "MODIFY_BIND_MOBILE";
		} else if ("BINDING_MOBILE".equals(type)) {
			templateKey = "MODIFY_BIND_MOBILE";
		} else if ("MODIFY_PASSWORD".equals(type)) {
			templateKey = "MODIFY_PASSWORD";
		} else if ("CASHDRAW".equals(type)) {
			templateKey = "";
		} else if ("WXLOGIN".equals(type)) {
			templateKey = "WXLOGIN";
		} else if ("RESETPASSWORD".equals(type)) {
			templateKey = "RESETPASSWORD";
		} else {
			templateKey = "";
		}

		Map<String, String> smsMap = new HashMap<String, String>();
		if (!templateKey.isEmpty()) {
			// 获取短信模版(数据库)
			querMap.put("templateKey", templateKey);
			querMap.put("templateType", "SMS");
			Map templateMap = usersDao.queryTemplate(querMap);
			if (null != templateMap) {
				conent = String.valueOf(templateMap.get("CONTENT"));
				// 替换参数
				smsMap.put("0", randomCode);
				for (int i = 0; i < smsMap.size(); i++) {
					conent = conent.replace("{" + i + "}", (CharSequence) smsMap.get(String.valueOf(i)));
				}
			}
		}

		ConfigSms ss = configSmsDao.selectByPrimaryKey("sms07004");
		if (conent.isEmpty()) {
			// 获取短信模版(文件)
			smsMap.put("0", randomCode);
			conent = ss.getSmsContext();
			conent = "【糯糯金融】" + conent;
			for (int i = 0; i < smsMap.size(); i++) {
				conent = conent.replace("{" + i + "}", (CharSequence) smsMap.get(String.valueOf(i)));
			}
		}
		// 第三方工程请求url
		String url = ThirdPartyEnvUtil.getValue("smsUrl");
		// 请求参数封装
		Map<String, String> paramMap = new HashMap<String, String>();
		paramMap.put("content", conent);
		paramMap.put("mobileListParams", map.getString("userMobile"));

		// 手动开关切通道
		String str_sd = "03"; // 01-手动(短信宝) 02-手动(月呈) 03-自动
		try {
			str_sd = sMSService.getJxCouponRate("send_sms_channel_sd");
		} catch (Exception e) {
			// TODO: handle exception
		}
		if ("01".equals(str_sd)) {
			paramMap.put("send_sms_channel", ss.getSmsChannel());
			/*
			 * if("RESETPASSWORD".equals(type)){
			 * paramMap.put("send_sms_channel","2"); }
			 */
		} else if ("02".equals(str_sd)) {
			paramMap.put("send_sms_channel", ss.getSmsChannel());
		} else {
			// ouyy 设置短信通道
			try {
				if (sendMesRecMap != null) {
					setSendSmsChannel(sendMesRecMap, paramMap);
				} else {
					paramMap.put("send_sms_channel", ss.getSmsChannel());
				}
			} catch (Exception e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		}
		// 发送短信
		querMap.put("randomCode", randomCode);
		// ouyy 记录短信通道标识
		String sendChannel = (String) paramMap.get("send_sms_channel");
		if (StringUtils.isBlank(sendChannel)) {
			sendChannel = "1";// 如果取不到就是不正常，设一个默认“１-短信宝”\
			// 如果是登录密码的标识 则调用月呈的短信

		} else {
			if ("RESETPASSWORD".equals(type)) {
				sendChannel = "2";
			}
		}
		querMap.put("sendChannel", sendChannel);
		addSendMsgRec(querMap);
		String requestParam = "keyRandom=KEY_RANDOM";
		String publicKeyParam = "";
		try {
			publicKeyParam = RSA.getPublick_Key_Encrypt(paramMap);
			requestParam = requestParam.replace("KEY_RANDOM", URLEncoder.encode(publicKeyParam, "utf-8"));
		} catch (Exception e) {
			logger.debug("公钥加密串：" + e);
		}

		// 发送短信消息
		String smsResult = CommonUtil.sendPostByHttp(url, requestParam);
		if (StringUtils.isBlank(smsResult)) {
			// 失败
			logger.error("发送短信失败：http请求中断");
			throw new RuntimeException("验证码获取失败！");
		} else {
			// 解析发送结果
			Map smsResultMap = JsonUtil.getMapFromJsonString(smsResult);
			if (null == smsResultMap || "sysException".equals(smsResultMap.get("rescode"))) {
				// 系统异常
				logger.error("发送短信失败：" + smsResultMap.get("resmsg_cn"));
				throw new RuntimeException("验证码获取失败！");
			} else if ("BusinessException".equals(smsResultMap.get("rescode"))) {
				// 业务异常
				logger.error("发送短信失败：" + smsResultMap.get("resmsg_cn"));
				throw new RuntimeException("验证码获取失败！");
			}
		}

		// 修改该用户当日发送次数
		usersDao.addJudgeCaptchaTime(querMap);
		// 保存验证码到DB
		try {
			sMSService.saveSMS(map.getString("userMobile"), conent, sendChannel);// send_sms_channel//
																			// 1-短信宝
																			// 2-月呈
		} catch (Exception e) {
			logger.error("/sendSMS/getSMS  短信保存失败，失败原因：" + e.getCause());
		}
		ResultDTO resultDTO = new ResultDTO<>(ResultCode.SUCCESS, "短信发送成功！");
		return resultDTO;
	}

	@Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class, readOnly = false)
	private void addSendMsgRec(Map<String, Object> querMap) throws Exception {
		usersDao.addSendMsgRec(querMap);
	}

	/**
	 * 设置发送短信的通道，规则按设置的时间内，如果再次发送，则切换通道
	 * 
	 * @param sendMesRecMap
	 *            //短信表
	 * @param paramMap
	 *            //传直
	 * @throws Exception
	 */
	private void setSendSmsChannel(Map sendMesRecMap, Map<String, String> paramMap) throws Exception {
		//
		String sc_send_channel = (String) sendMesRecMap.get("SEND_CHANNEL");// 上次发送短信的通道
		logger.debug("sc_send_channel==" + sc_send_channel);
		String send_sms_channel_time = "";// 短信渠道切换时间参数(单位：秒)
		try {
			send_sms_channel_time = sMSService.getJxCouponRate("send_sms_channel_time");
			logger.debug("send_sms_channel_time==" + send_sms_channel_time);
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			send_sms_channel_time = "0";// 如果异常设置成零秒
			logger.error("获取短信渠道切换时间参数出错：" + CommonUtil.printStackTraceToString(e1));

		}
		String send_sms_channel = "2";// 需要传给第三方工程的通道标识
		// 判断参数设置的秒数之同更改发送的通道1-短信宝 2-月呈
		Date sc_send_Time = (Date) sendMesRecMap.get("END_SETUP_TIME");// 上次发送的时间
		int timeZh = 0;
		try {
			timeZh = Integer.parseInt(send_sms_channel_time);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		Date zh_codeTime = new Date(sc_send_Time.getTime() + timeZh * 1 * 1000);// 加上timeZh后的时间
		Date now = usersDao.querySysDate();// 数据库系统当前时间
		if (now.getTime() <= zh_codeTime.getTime()) {
			if ("1".equals(sc_send_channel)) {
				send_sms_channel = "2";
			} else if ("2".equals(sc_send_channel)) {
				send_sms_channel = "1";
			}
		} else if (!StringUtils.isBlank(sc_send_channel)) {
			send_sms_channel = sc_send_channel;
		}
		paramMap.put("send_sms_channel", send_sms_channel);//
		logger.debug("send_sms_channel==" + send_sms_channel);
	}

	/**
	 * 校验验证码主处理 同时，添加170开头的手机号段暂不支持注册校验，add by zhouyj2016-12-16
	 */
	@Override
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class, readOnly = false)
	public ResultDTO checkCaptcha(JSONObject params) throws Exception {

		Map<String, Object> querMap = new HashMap<String, Object>();
		String userMobile = params.getString("phoneNum");
		if(StringUtils.isEmpty(userMobile))
			userMobile = params.getString("userName");
		querMap.put("userMobile", userMobile);
		querMap.put("setupFlag", params.getString("setupFlag"));

		Map<String, Object> paramsMap = new HashMap<String, Object>();
		paramsMap.put("mobile", userMobile);
		User user = usersDao.getUserByParm(paramsMap);

		if (user == null) {
			// 170开头的手机号段暂不支持注册--开始
			String condition = "";
			try {
				condition = activityService.findParamValueByName("register_forbidden_mobile");
				logger.info("查询系统参数表，获取限制注册手机号限制条件：" + condition);
			} catch (Exception e1) {
				logger.error("获取禁止注册手机号参数异常", e1);
				e1.printStackTrace();
			}
			if ((!"".equals(condition)) && (!CommonUtil.registerPhoneLimitCheck(params.getString("phoneNum"), condition))) {
				logger.info("系统限制注册手机号：" + params.getString("phoneNum") + "，限制条件：" + condition);
				Map<String, Object> errorMap = errorMessageService.getErrorMessage("EM000000027");
				String errMsg = getErrorMsg(errorMap);
				return new ResultDTO(ResultCode.FAILED,errMsg);
			}
			// 170开头的手机号段暂不支持注册--结束
		}

		// 从数据库中获取验证码
		Map sendMesRecMap = usersDao.querySendMesRec(querMap);

		if (null == sendMesRecMap || null == sendMesRecMap.get("VALICODE")
				|| StringUtils.isBlank(String.valueOf(sendMesRecMap.get("VALICODE")))) {
			// 无验证码的情况
			logger.error("短信发送记录表中不存在数据，校验验证码失败！");
			return new ResultDTO(ResultCode.FAILED,Message.CnDescriptionExpression.CHECK_CAPTCHA_FAILED);
		}

		// 验证码存在的情况下判断失效时间(10分钟有效)
		logger.debug("请求手机号：" + params.getString("phoneNum") + "验证码：" + sendMesRecMap.get("VALICODE") + "创建时间"
				+ sendMesRecMap.get("END_SETUP_TIME"));
		Date codeTime = (Date) sendMesRecMap.get("END_SETUP_TIME");
		Date codeTime_10 = new Date(codeTime.getTime() + 600000);// 10分钟后的时间
		Date now = usersDao.querySysDate();

		// 比較大小
		if (now.getTime() > codeTime_10.getTime()) {
			// 超过10分钟，无效
			logger.error("请求手机号：" + params.getString("phoneNum") + "验证码超过10分钟");

			// 数据库中的短信标志设为无效
			usersDao.setInvalidFlag(querMap);
			return new ResultDTO(ResultCode.FAILED,Message.CnDescriptionExpression.CAPTCHA_TIMEOUT);
		}

		if (!params.getString("checkCode").equals(sendMesRecMap.get("VALICODE"))) {
			logger.error("验证码错误，输入验证码：" + params.getString("checkCode") + "正确验证码：" + sendMesRecMap.get("VALICODE"));
			return new ResultDTO(ResultCode.FAILED,Message.CnDescriptionExpression.CHECK_CAPTCHA_FAILED);
		}

		// 数据库中的短信标志设为无效
		// usersDao.setInvalidFlag(querMap);
		// 处理成功标志位
		return ResultConstant.SUCCESS;
	}

	/**
	 * 注册(T_TUSER表和USER_INFO表)
	 */
	@Override
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class, readOnly = false)
	public void addUsers(User user) throws Exception {
		user.setEmail_validate("N");// 邮箱是否已经通过验证(Y/N)
		user.setEnable("Y");// 是否启用(Y/N)
		user.setIdcard_validate("N");// 身份证是否通过验证(Y/N)
		user.setMobile_validate("Y");// 手机是否通过验证(Y/N)

		String loginId = this.usersDao.getUserNickNameSeqNextVal();
		user.setNick_name(loginId);// 昵称
		user.setReg_time(new Date());// 注册日期
		user.setUserinfo_finished("N");// 个人信息是否完成(Y/N)
		user.setUser_type("NORMAL_USER");// 用户类型(NORMAL_USER:普通用户;AGENCY_USER:机构用户;VENTURE_FUNDS:机构风险金用户;SYSTEM_USER:系统用户;AGENCY_REPAY:机构还款用户;AGENCY_REVENUE:机构营收用户;)????

		// String currentFloatRateChannel = "0";
		// String fixFloatRateChannel = "0";
		// String expires = "0";
		/**
		 * 根据用户传入的渠道名称获取渠道id
		 */
		String channelId = null;
		Map<String, Object> channelInfo = this.usersDao.getChannelInfo(user.getChannel());
		if (null == channelInfo) {
			channelInfo = this.usersDao.getChannelInfo("OTHERS");
			channelId = channelInfo.get("ID").toString();
			if (null == channelId) {
				logger.debug("注册时渠道id获取失败");
				throw new Exception("注册时渠道id获取失败");
			}
		} else {
			channelId = channelInfo.get("ID").toString();
			// currentFloatRateChannel =
			// channelInfo.get("CURRENT_FLOAT_RATE") == null ? "0" :
			// channelInfo.get("CURRENT_FLOAT_RATE").toString();
			// fixFloatRateChannel =
			// channelInfo.get("FIX_FLOAT_RATE") == null ? "0" :
			// channelInfo.get("FIX_FLOAT_RATE").toString();
			// expires = channelInfo.get("EXPIRES") == null ? "0" :
			// channelInfo.get("EXPIRES").toString();
		}

		user.setUtm_source(channelId);
		user.setWorkinfo_finished("N");// 工作信息是否完成(Y/N)
		user.setLogin_error_times(8);// 用户登录密码输入错误次数(可空)
		user.setIs_create_acct("0");// 是否已创建账户体系结构（0、未创建1、已创建）(可空)
		user.setShow_login_id("id_" + loginId);

		Map<String, Object> code = new HashMap<String, Object>();
		// 邀请码
		this.usersDao.getInvitationCode(code);
		// user.setInvitation_code(String.valueOf(code.get("avc_out_invitation_code")).toUpperCase());
		user.setInvitation_code(user.getMobile());
		user.setSina_idcard_validate("N");
		user.setIs_create_sina_acct("N");
		this.usersDao.addUser(user);
		// 抽取用户id
		int id = user.getId();

		UserInfo insertUserInfo = new UserInfo();
		insertUserInfo.setUser_id(id);// 所属用户（唯一）
		insertUserInfo.setPhone_no(user.getMobile());// 用户电话号(可空)

		this.usersDao.addUserInfo(insertUserInfo);

		// // 用户渠道等级积分表写入
		// UserChannelPoint userChannelPoint = new UserChannelPoint();
		// userChannelPoint.setUserId(String.valueOf(id));
		// userChannelPoint.setUserChannel(channelId);
		// userChannelPoint.setCurrentFloatRateChannel(currentFloatRateChannel);
		// userChannelPoint.setFixFloatRateChannel(fixFloatRateChannel);
		//
		// // 有效期
		// if (expires == null || "".equals(expires) || "null".equals(expires))
		// {
		// expires = "0";
		// }
		// if (!"0".equals(expires)) {
		// SimpleDateFormat hmsFormat = new SimpleDateFormat("yyyyMMdd");
		// Date date = new Date();
		// String nowYmd = hmsFormat.format(date);
		// Calendar cal = Calendar.getInstance();
		// cal.setTime(date);
		// cal.add(Calendar.DATE,Integer.parseInt(expires));
		// userChannelPoint.setStartTime(nowYmd);
		// userChannelPoint.setEndTime(hmsFormat.format(cal.getTime()));
		// }
		// userChannelPointDao.addChannelPoint(userChannelPoint);

		insertUserQuickWithdrawInfo(String.valueOf(id));

		/*
		 * // UCenter同步注册 try { Client uc = new Client(); String $returns =
		 * uc.uc_user_register(user.getMobile(), user.getPassword_cash(),
		 * user.getMobile() + "@hotmail.com", "", "", user.getMobile()); int
		 * $uid = Integer.parseInt($returns); if ($uid <= 0) { if ($uid == -1) {
		 * logger.info("=======Ucenter:用户名不合法=========="); // throw new
		 * Exception("用户名不合法"); } else if ($uid == -2) {
		 * logger.info("=======Ucenter:包含要允许注册的词语=========="); // throw new
		 * Exception("包含要允许注册的词语"); } else if ($uid == -3) {
		 * logger.info("=======Ucenter:用户名已经存在=========="); // throw new
		 * Exception("用户名已经存在"); } else if ($uid == -4) {
		 * logger.info("=======Ucenter:格式有误=========="); // throw new
		 * Exception("Email 格式有误"); } else if ($uid == -5) {
		 * logger.info("=======Ucenter:不允许注册=========="); // throw new
		 * Exception("Email 不允许注册"); } else if ($uid == -6) {
		 * logger.info("=======Ucenter:已经被注册=========="); // throw new
		 * Exception("该 Email 已经被注册"); } else {
		 * logger.info("=======Ucenter:未定义=========="); // throw new
		 * Exception("未定义"); } } else { System.out.println("OK:" + $returns); }
		 * } catch (Exception e) { e.printStackTrace(); }
		 */
	}

	/**
	 * 铃铛双十一添加用户 flg:说明: 是否更新 t_user表
	 */
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class, readOnly = false)
	@Override
	public void ldAddUsers(User user, boolean flg) throws Exception {
		if (flg) {
			user.setEmail_validate("N");// 邮箱是否已经通过验证(Y/N)
			user.setEnable("Y");// 是否启用(Y/N)
			user.setIdcard_validate("N");// 身份证是否通过验证(Y/N)
			user.setMobile_validate("Y");// 手机是否通过验证(Y/N)

			String loginId = this.usersDao.getUserNickNameSeqNextVal();
			user.setNick_name(loginId);// 昵称
			user.setReg_time(new Date());// 注册日期
			user.setUserinfo_finished("N");// 个人信息是否完成(Y/N)
			user.setUser_type("NORMAL_USER");// 用户类型(NORMAL_USER:普通用户;AGENCY_USER:机构用户;VENTURE_FUNDS:机构风险金用户;SYSTEM_USER:系统用户;AGENCY_REPAY:机构还款用户;AGENCY_REVENUE:机构营收用户;)????

			/**
			 * 根据用户传入的渠道名称获取渠道id
			 */
			Integer channelId = this.usersDao.getChannelId(user.getChannel());
			if (null == channelId) {
				Integer channelId2 = this.usersDao.getChannelId("OTHERS");
				if (null == channelId2) {
					logger.debug("注册时渠道id获取失败");
					throw new Exception("注册时渠道id获取失败");
				} else {
					user.setUtm_source(channelId2 + "");// 用户来源（渠道ID）
				}
			} else {
				user.setUtm_source(channelId + "");// 用户来源（渠道ID）
			}

			user.setWorkinfo_finished("N");// 工作信息是否完成(Y/N)
			user.setLogin_error_times(8);// 用户登录密码输入错误次数(可空)
			user.setIs_create_acct("0");// 是否已创建账户体系结构（0、未创建1、已创建）(可空)
			user.setShow_login_id("id_" + loginId);

			user.setInvitation_code(user.getMobile());
			user.setSina_idcard_validate("N");
			user.setIs_create_sina_acct("N");
			/*
			 * t_user表创建
			 */
			this.usersDao.addUser(user);
		} else {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("mobile", user.getMobile());
			user = usersDao.getUserByParm(map);
		}
		// 抽取用户id
		int id = user.getId();

		// 考虑到会有老用户的情况
		UserInfo userInfo = usersDao.getUserInfo(String.valueOf(id));
		if (userInfo == null) {
			UserInfo insertUserInfo = new UserInfo();
			insertUserInfo.setUser_id(id);// 所属用户（唯一）
			insertUserInfo.setPhone_no(user.getMobile());// 用户电话号(可空)
			/*
			 * user_info表创建
			 */
			this.usersDao.addUserInfo(insertUserInfo);
		}

		/*
		 * 用户主账户创建
		 */
		// 创建主账户
		String transCode = "E300053";
		Map<String, Object> coreMap = new HashMap<String, Object>();
		coreMap.put("userid", user.getId());
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");
		String sysdate = sdf.format(new Date());
		coreMap.put("sysdate", sysdate);
		coreMap.put("identitynum", "");
		coreMap.put("useralias", user.getNick_name());
		coreMap.put("realname", "");
		coreMap.put("email", user.getEmail() == null ? "" : user.getEmail());
		coreMap.put("phoneno", user.getMobile() == null ? "" : user.getMobile());

		String jsonStr = CommonUtil.constructJsonStr(transCode, user.getId().toString(), coreMap);
		String rtnStr = CommonUtil.getCoreValue(jsonStr);

		JSONObject jsonObject = JSONObject.parseObject(rtnStr);
		String coreRescode = jsonObject.getString("rescode");
		if (coreRescode.equals(Consts.SUCCESS_CODE)) {
			// 更新用户的is_create_acct为1
			user.setIs_create_acct("1");
			this.usersDao.updateUserIsCreateAcctAfterLLPayAuth(user);
		} else {
			throw new Exception("创建主账户错误！");
		}
		/*
		 * // UCenter同步注册 try { Client uc = new Client(); String $returns =
		 * uc.uc_user_register(user.getMobile(), user.getPassword_cash(),
		 * user.getMobile() + "@hotmail.com", "", "", user.getMobile()); int
		 * $uid = Integer.parseInt($returns); if ($uid <= 0) { if ($uid == -1) {
		 * logger.info("=======Ucenter:用户名不合法=========="); // throw new
		 * Exception("用户名不合法"); } else if ($uid == -2) {
		 * logger.info("=======Ucenter:包含要允许注册的词语=========="); // throw new
		 * Exception("包含要允许注册的词语"); } else if ($uid == -3) {
		 * logger.info("=======Ucenter:用户名已经存在=========="); // throw new
		 * Exception("用户名已经存在"); } else if ($uid == -4) {
		 * logger.info("=======Ucenter:格式有误=========="); // throw new
		 * Exception("Email 格式有误"); } else if ($uid == -5) {
		 * logger.info("=======Ucenter:不允许注册=========="); // throw new
		 * Exception("Email 不允许注册"); } else if ($uid == -6) {
		 * logger.info("=======Ucenter:已经被注册=========="); // throw new
		 * Exception("该 Email 已经被注册"); } else {
		 * logger.info("=======Ucenter:未定义=========="); // throw new
		 * Exception("未定义"); } } else { System.out.println("OK:" + $returns); }
		 * } catch (Exception e) { e.printStackTrace(); }
		 */
	}

	/**
	 * 核心增加铃铛用户
	 * 
	 * @throws Exception
	 */
	@Override
	public Map<String, Object> coreLDAddUser(User user, boolean flg) throws Exception {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		/*
		 * 调用核心创建用户相关信息
		 */
		String transCode = "E300056";
		Map<String, Object> coreMap = new HashMap<String, Object>();
		coreMap.put("mobileNumber", user.getMobile());
		coreMap.put("channel", user.getChannel());
		coreMap.put("ip", user.getLastest_login_ip());
		coreMap.put("token", user.getLogin_token());
		coreMap.put("flg", flg);

		String jsonStr = CommonUtil.constructJsonStr(transCode, null, coreMap);
		String rtnStr = CommonUtil.getCoreValue(jsonStr);

		JSONObject jsonObject = JSONObject.parseObject(rtnStr);

		String rescode = jsonObject.getString("rescode");
		resultMap.put("rescode", rescode);

		if (rescode.equals(Consts.SUCCESS_CODE)) {
			resultMap.put("userId", jsonObject.getString("userId"));
		}

		return resultMap;
	}

	/**
	 * 登陆(T_TUSER表和USER_INFO表)
	 */
	@Override
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class, readOnly = false)
	public ResultDTO dealLogin(JSONObject params) throws Exception {

		Map<String,Object> jsonMap = new HashMap<>();
		String userName = params.getString("userName");// 用户名
		String password = params.getString("password");// 密码 (不用)
		String type = params.getString("type");// 登陆类型：手机或者邮箱
		ResultDTO result;

		String passwordMd5 = MD5.md5(password);
		List<GetUserInfo> userInfo = usersDao.loginCheck(userName, passwordMd5, type);

		if (userInfo == null || userInfo.size() <= 0) {
			logger.error("登陆处理中用户或者密码错误！");
			result = new ResultDTO(ResultCode.FAILED,
					Message.CnDescriptionExpression.USERORPASSWORD_IS_INCORRECT);
		} else if (userInfo.size() > 1) {
			logger.debug("登陆处理中用户存在多个邮箱");
			result = new ResultDTO(ResultCode.FAILED,
					Message.CnDescriptionExpression.MULTIPLE_MAILBOXES_EXISTED);
		} else {
			// 用户存在的情况下
			jsonMap.put("userId", userInfo.get(0).getId());
			jsonMap.put("userName", userName);
			if(StringUtils.isEmpty(userInfo.get(0).getPassword_cash())){
				jsonMap.put("passwordCashValidate","N");
			}else{
				jsonMap.put("passwordCashValidate","Y");
			}
			if ("Y".equals(userInfo.get(0).getIdcard_validate()) && "1".equals(userInfo.get(0).getIs_create_acct())) {
				jsonMap.put("identityName", userInfo.get(0).getReal_name());
				jsonMap.put("idCard", userInfo.get(0).getId_card());
				jsonMap.put("idcardValidate", "Y");
			} else {
				jsonMap.put("identityName", "");
				jsonMap.put("idCard", "");
				jsonMap.put("idcardValidate", "N");
			}

			// 查询是否绑定银行卡
			HashMap<String, Object> userPayCdParam = new HashMap<String, Object>();
			userPayCdParam.put("isValid", "Y");
			userPayCdParam.put("userId", userInfo.get(0).getId());
			userPayCdParam.put("isBinding", "Y");
			UserBankCardVo userRecePayCard = centerService.getRecePayBank(userPayCdParam);
			if (null == userRecePayCard) {
				jsonMap.put("bankCardValidate", "N");
			} else {
				jsonMap.put("bankCardValidate", "Y");
			}

			// 头像原图
			String ftpPathOriginal = userInfo.get(0).getImage_icon_original();
			// 头像缩略图
			String ftpPathDispose = userInfo.get(0).getImage_icon_dispose();
			String token = "login" + "_" + CommonUtil.getUuid();

			jsonMap.put("ftpPathOriginal", ftpPathOriginal);
			jsonMap.put("ftpPathDispose", ftpPathDispose);
			jsonMap.put("emailValidate", userInfo.get(0).getEmail_validate());
			jsonMap.put("mobileValidate", userInfo.get(0).getMobile_validate());
			jsonMap.put("email", userInfo.get(0).getEmail());
			jsonMap.put("mobile", userInfo.get(0).getMobile());
			jsonMap.put("uuid", token);

			// 登陆成功 更新最后登录时间,ip
			Map<String, String> paramsMap = new HashMap<>();
			paramsMap.put("uuid", token);
			paramsMap.put("userId", userInfo.get(0).getId() + "");
			paramsMap.put("ip", params.getString("ip"));
			// 根据用户自增ID更新用户最后登录时间
			usersDao.updateLastLoginTime(userInfo.get(0).getId() + "", params.getString("ip"));
			// uuid更新
			securityDao.updLoginTokenStr(paramsMap);
			Map<String, Object> cardReqMap = new HashMap<>();
			cardReqMap.put("userId", userInfo.get(0).getId() + "");
			// 判断用户是否进行绑卡
			List<UserRecePayCard> cardList = this.userCardDao.queryUserCardInfoByUserId(cardReqMap);

			String isBindingCard = "";
			if (null == cardList || cardList.size() == 0) {
				isBindingCard = "N";
			} else {
				isBindingCard = "Y";
			}
			// 恢复该用户密码输入次数超限
			usersDao.updateLoginErrorTimeBack(userName);

			jsonMap.put("isBindingCard", isBindingCard);
			jsonMap.put("yzToken", TokenUtil.genToken(jsonMap));
			result = new ResultDTO<>(ResultCode.SUCCESS);
			result.setRecord(jsonMap);
		}
		return result;
	}

	/**
	 * 登陆(T_TUSER表和USER_INFO表)WEIXIN
	 */
	@Override
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class, readOnly = false)
	public String dealLoginByWx(Map<String, String> map) throws Exception {
		Map<String, Object> jsonMap = new HashMap<String, Object>();

		String userName = map.get("userName");// 用户名
		String type = map.get("type");// 登陆类型：手机或者邮箱
		String result = "";

		List<GetUserInfo> userInfo = usersDao.loginCheck(userName, "", type);

		if (userInfo == null || userInfo.size() <= 0) {
			result = CommonUtil.setResultStringCn(new HashMap<String, Object>(), Consts.CHECK_CODE, "",
					Message.CnDescriptionExpression.MOBILE_NOT_EXIST);
		} else if (userInfo.size() > 1) {
			logger.debug("登陆处理中用户存在多个邮箱");
			result = CommonUtil.setResultStringCn(new HashMap<String, Object>(), Consts.CHECK_CODE, "",
					Message.CnDescriptionExpression.MULTIPLE_MAILBOXES_EXISTED);
		} else {
			// 用户存在的情况下
			jsonMap.put("userId", userInfo.get(0).getId());
			jsonMap.put("userName", userName);

			if ("Y".equals(userInfo.get(0).getIdcard_validate()) && "1".equals(userInfo.get(0).getIs_create_acct())) {
				jsonMap.put("identityName", userInfo.get(0).getReal_name());
				jsonMap.put("idCard", userInfo.get(0).getId_card());
				jsonMap.put("idcardValidate", "Y");
			} else {
				jsonMap.put("identityName", "");
				jsonMap.put("idCard", "");
				jsonMap.put("idcardValidate", "N");
			}

			// 查询是否绑定银行卡
			HashMap<String, Object> userPayCdParam = new HashMap<String, Object>();
			userPayCdParam.put("isValid", "Y");
			userPayCdParam.put("userId", userInfo.get(0).getId());
			userPayCdParam.put("isBinding", "Y");
			UserBankCardVo userRecePayCard = centerService.getRecePayBank(userPayCdParam);
			if (null == userRecePayCard) {
				jsonMap.put("bankCardValidate", "N");
			} else {
				jsonMap.put("bankCardValidate", "Y");
			}

			// 头像原图
			String ftpPathOriginal = userInfo.get(0).getImage_icon_original();
			// 头像缩略图
			String ftpPathDispose = userInfo.get(0).getImage_icon_dispose();
			String token = "login" + "_" + CommonUtil.getUuid();

			jsonMap.put("ftpPathOriginal", ftpPathOriginal);
			jsonMap.put("ftpPathDispose", ftpPathDispose);
			jsonMap.put("emailValidate", userInfo.get(0).getEmail_validate());
			jsonMap.put("mobileValidate", userInfo.get(0).getMobile_validate());
			jsonMap.put("email", userInfo.get(0).getEmail());
			jsonMap.put("mobile", userInfo.get(0).getMobile());
			jsonMap.put("uuid", token);

			// 登陆成功 更新最后登录时间,ip
			Map<String, String> paramsMap = new HashMap<String, String>();
			paramsMap.put("uuid", token);
			paramsMap.put("userId", userInfo.get(0).getId() + "");
			paramsMap.put("ip", map.get("ip"));
			// 根据用户自增ID更新用户最后登录时间
			usersDao.updateLastLoginTime(userInfo.get(0).getId() + "", map.get("ip"));
			// uuid更新
			securityDao.updLoginTokenStr(paramsMap);

			map.put("userId", userInfo.get(0).getId() + "");

			result = CommonUtil.setResultStringCn(jsonMap, Consts.SUCCESS_CODE, Consts.SUCCESS_DESCRIBE, "");
		}
		return result;
	}

	@Override
	public User getUserByParm(Map<String, Object> map) throws Exception {
		// TODO Auto-generated method stub
		return usersDao.getUserByParm(map);
	}

	/**
	 * 连连支付-实名认证
	 * 
	 * @throws Exception
	 */
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class, readOnly = false)
	@Override
	public Map<String, Object> getAuth(Map<String, String> map) throws Exception {
		Map<String, Object> returnMap = new HashMap<String, Object>();
		Map<String, String> requestMap = new HashMap<String, String>();
		String idCard = map.get("idCard").toUpperCase();
		String nameCard = map.get("nameCard").replace(" ", "");
		requestMap.put("idCard", idCard);
		requestMap.put("nameCard", nameCard);
		String userId = map.get("userId");

		// 更新t_User表数据
		User user = this.usersDao.getUserDetail(userId);

		String idCardValidate = user.getIdcard_validate();
		if (idCardValidate.equals("Y")) {
			returnMap.put("rescode", Consts.CHECK_CODE);
			returnMap.put("resmsg_cn", "您已实名认证成功，请勿重复实名认证！");
			return returnMap;
		}

		// 增加身份证号check判断 是否使用过该身份证号码
		Map<String, Object> idCardReqMap = new HashMap<String, Object>();
		idCardReqMap.put("identitynum", idCard);
		Integer idCardCount = this.usersDao.checkIdCardIsExist(idCardReqMap);
		if (idCardCount > 0) {
			returnMap.put("rescode", Consts.CHECK_CODE);
			returnMap.put("resmsg_cn", "该身份证号码已经被使用！");
			return returnMap;
		}

		// 查询用户当日实名次数是否超限
		Map<String, Object> authCountMap = new HashMap<String, Object>();
		authCountMap.put("userId", userId);
		UserAuthentication currentAuth = this.userAuthenticationDao.queryCurrentUserAuthentication(authCountMap);

		if (currentAuth != null) {
			// 从参数表获取
			Integer authLimitNumber = StringUtils.isBlank(findParamValueByName("auth_limit_number")) ? 3
					: Integer.parseInt(findParamValueByName("auth_limit_number"));
			if (currentAuth.getAuth_count() >= authLimitNumber) {
				returnMap.put("rescode", Consts.CHECK_CODE);
				returnMap.put("resmsg_cn", "当日实名次数已超限，请联系客服！");
				return returnMap;
			} else {
				// 更新表
				currentAuth.setAuth_count(currentAuth.getAuth_count() + 1);
				Integer updateCount = this.userAuthenticationDao.updateUserAuthCurrent(currentAuth);
				if (updateCount == 0) {
					returnMap.put("rescode", Consts.CHECK_CODE);
					returnMap.put("resmsg_cn", "请联系客服！");
					return returnMap;
				}
			}
		} else {
			// 插入表
			currentAuth = new UserAuthentication();
			currentAuth.setUser_id(Integer.parseInt(userId));
			currentAuth.setAuth_count(1);
			Integer insertCount = this.userAuthenticationDao.insertUserAuthCurrent(currentAuth);
			if (insertCount == 0) {
				returnMap.put("rescode", Consts.CHECK_CODE);
				returnMap.put("resmsg_cn", "请联系客服！");
				return returnMap;
			}
		}

		// 生成订单号
		Map<String, String> authResult = new HashMap<String, String>();

		// 查询ProductCode的Service名称
		Map<String, String> tprParamMap = new HashMap<String, String>();
		tprParamMap.put("productCode", "realname");
		tprParamMap.put("bankName", "-1");
		List<ThirdProductRoute> tprList = this.thirdProductRouteDao.getThirdProductRoutes(tprParamMap);

		if (tprList == null || tprList.size() == 0) {
			returnMap.put("rescode", Consts.ERROR_CODE);
			returnMap.put("resmsg_cn", "实名认证异常，请联系客服！");
			return returnMap;
		}

		// ThirdProductRoute tpr = tprList.get(0);
		// 根据权重路由一个实名渠道
		ThirdProductRoute tpr = CommonUtil.lottery(tprList, "weight");

		Map<String, String> thirdPartyParams = new HashMap<String, String>();
		thirdPartyParams.put("productCode", tpr.getThirdProductCode());
		thirdPartyParams.put("realName", nameCard);
		thirdPartyParams.put("identityCard", idCard);

		String logInfo = "实名认证" + user.getMobile();
		authResult = ThirdPartyEnvUtil.invoke(logInfo, thirdPartyParams, "/route/auth");

		if (authResult == null || "sysException".equals(authResult.get("rescode"))) {
			throw new RuntimeException("实名认证失败");
		} else if ("BusinessException".equals(authResult.get("rescode"))) {
			throw new RuntimeException(String.valueOf(authResult.get("resmsg_cn")));
		}
		String rescode = authResult.get("rescode");

		// String rescode = "00"; String resmsg = "交易成功";

		if (rescode.equals("00001")) {
			String authOrderNo = authResult.get("reqOrderId");
			// String llpayOrderNo = outOrderNo;

			user.setId(Integer.parseInt(userId));
			user.setLlpay_idcard_vaildate("Y");
			user.setLlpay_order_no(authOrderNo);
			user.setLlpay_outorder_no(authOrderNo);
			user.setIdcard_validate("Y");

			this.usersDao.updateUserInfoAfterLLPayAuth(user);

			// 用户身份证认证表
			IdcardInfo idCardInfo = new IdcardInfo();

			// 更新User_info表数据
			UserInfo userInfo = this.usersDao.getUserInfo(userId);
			// 生日
			String date = IDCard.getBirthDay(idCard);
			SimpleDateFormat formatz = new SimpleDateFormat("yyyyMMdd");
			Date birthDay = formatz.parse(date);
			userInfo.setBirthday(birthDay);
			// 性别
			String sex = IDCard.getSex(idCard);
			userInfo.setGender(sex);
			userInfo.setId_card(idCard);
			userInfo.setReal_name(nameCard);
			userInfo.setUser_id(Integer.parseInt(userId));

			idCardInfo.setIdno(idCard);// 身份证
			idCardInfo.setName(nameCard);// 真实姓名
			idCardInfo.setUser_id(Integer.parseInt(userId));
			idCardInfo.setBirth(birthDay);
			// 性别
			idCardInfo.setGender(sex);

			this.usersDao.updateUserIdCardAfterLLPayAuth(userInfo);

			// 保存用户身份证认证表
			optionDao.insertIdCardInfo(idCardInfo);
			// 判断如果是铃铛用户 则只做主账户更新操作
			String utmSource = user.getUtm_source();
			if (!(utmSource.equals("92") || utmSource.equals("93"))) {
				// 判断用户是否存在主账户
				String isCreateAcct = user.getIs_create_acct();
				if (isCreateAcct.equals("1")) {
					// 根据user_id更新主账户
					String transCode = "E300055";
					Map<String, Object> coreMap = new HashMap<String, Object>();
					coreMap.put("userid", userId);
					SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");
					String sysdate = sdf.format(new Date());
					coreMap.put("sysdate", sysdate);
					coreMap.put("identitynum", idCard);
					coreMap.put("useralias", user.getNick_name());
					coreMap.put("realname", nameCard);
					coreMap.put("email", user.getEmail() == null ? "" : user.getEmail());
					coreMap.put("phoneno", user.getMobile() == null ? "" : user.getMobile());
					String jsonStr = CommonUtil.constructJsonStr(transCode, userId, coreMap);
					String rtnStr = CommonUtil.getCoreValue(jsonStr);

					JSONObject jsonObject = JSONObject.parseObject(rtnStr);
					String coreRescode = jsonObject.getString("rescode");
					if (coreRescode.equals(Consts.SUCCESS_CODE)) {
						returnMap.put("rescode", Consts.SUCCESS_CODE);
						returnMap.put("resmsg", Consts.SUCCESS_DESCRIBE);
					} else {
						returnMap.put("rescode", Consts.ERROR_CODE);
						returnMap.put("resmsg_cn", "更新主账户报错");
						throw new Exception("更新主账户报错");
					}
				} else {
					// 创建主账户
					String transCode = "E300053";
					Map<String, Object> coreMap = new HashMap<String, Object>();
					coreMap.put("userid", userId);
					SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");
					String sysdate = sdf.format(new Date());
					coreMap.put("sysdate", sysdate);
					coreMap.put("identitynum", idCard);
					coreMap.put("useralias", user.getNick_name());
					coreMap.put("realname", nameCard);
					coreMap.put("email", user.getEmail() == null ? "" : user.getEmail());
					coreMap.put("phoneno", user.getMobile() == null ? "" : user.getMobile());

					String jsonStr = CommonUtil.constructJsonStr(transCode, userId, coreMap);
					String rtnStr = CommonUtil.getCoreValue(jsonStr);

					JSONObject jsonObject = JSONObject.parseObject(rtnStr);
					String coreRescode = jsonObject.getString("rescode");
					if (coreRescode.equals(Consts.SUCCESS_CODE)) {
						// 更新用户的is_create_acct为1
						user.setIs_create_acct("1");
						this.usersDao.updateUserIsCreateAcctAfterLLPayAuth(user);

						returnMap.put("rescode", Consts.SUCCESS_CODE);
						returnMap.put("resmsg", Consts.SUCCESS_DESCRIBE);
					} else {
						returnMap.put("rescode", Consts.ERROR_CODE);
						returnMap.put("resmsg_cn", "该身份证号码已被使用!");
						throw new Exception("该身份证号码已被使用!");
					}
				}

			} else {
				// 根据user_id更新主账户
				String transCode = "E300055";
				Map<String, Object> coreMap = new HashMap<String, Object>();
				coreMap.put("userid", userId);
				SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");
				String sysdate = sdf.format(new Date());
				coreMap.put("sysdate", sysdate);
				coreMap.put("identitynum", idCard);
				coreMap.put("useralias", user.getNick_name());
				coreMap.put("realname", nameCard);
				coreMap.put("email", user.getEmail() == null ? "" : user.getEmail());
				coreMap.put("phoneno", user.getMobile() == null ? "" : user.getMobile());
				String jsonStr = CommonUtil.constructJsonStr(transCode, userId, coreMap);
				String rtnStr = CommonUtil.getCoreValue(jsonStr);

				JSONObject jsonObject = JSONObject.parseObject(rtnStr);
				String coreRescode = jsonObject.getString("rescode");
				if (coreRescode.equals(Consts.SUCCESS_CODE)) {
					returnMap.put("rescode", Consts.SUCCESS_CODE);
					returnMap.put("resmsg", Consts.SUCCESS_DESCRIBE);
				} else {
					returnMap.put("rescode", Consts.ERROR_CODE);
					returnMap.put("resmsg_cn", "更新主账户报错");
					throw new Exception("更新主账户报错!");
				}
			}

		} else {
			returnMap.put("rescode", Consts.ERROR_CODE);
			returnMap.put("resmsg_cn", "身份证号码或姓名输入有误，请确认后重新输入！");
		}
		return returnMap;
	}

	/**
	 * 铃铛双十一活动-查询用户活动信息
	 */
	@Override
	public Map<String, Object> findUserActivityInfo(Map<String, String> map) {
		String mobile = map.get("mobile");
		Map<String, Object> paramsMap = new HashMap<String, Object>();
		paramsMap.put("mobile", mobile);

		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			List<UserLDActivityInfo> activityInfoList = activityDao.findActivityInfoByParm(paramsMap);
			resultMap.put("mobileNumber", mobile);
			resultMap.put("rescode", Consts.SUCCESS_CODE);
			resultMap.put("resmsg", "查询成功");
			if (activityInfoList != null && activityInfoList.size() > 0) {
				UserLDActivityInfo activityInfo = activityInfoList.get(0);
				resultMap.put("activityShareFlg", activityInfo.getShare_validate());
				resultMap.put("activityKCodeFlg", activityInfo.getKey_code_use_validate());
				resultMap.put("activityPraiseFlg", activityInfo.getPraise_validate());
				resultMap.put("cardNo", activityInfo.getCard_no());
				resultMap.put("keyCode", activityInfo.getKey_code());
				resultMap.put("keyCodeExchangeAmt", activityInfo.getKey_code_exchange_amt());
				resultMap.put("keyCodeExchangeLbAmt", activityInfo.getKey_code_exchange_lb_amt());
				resultMap.put("step1OrderId", activityInfo.getStep1_order_id());
				resultMap.put("keyCodeUseTime", activityInfo.getKey_code_use_time());
			} else {
				resultMap.put("activityShareFlg", "N");
				resultMap.put("activityKCodeFlg", "N");
				resultMap.put("activityPraiseFlg", "N");
				resultMap.put("cardNo", "");
				resultMap.put("keyCode", "");
				resultMap.put("keyCodeExchangeAmt", "");
				resultMap.put("keyCodeExchangeLbAmt", "");
				resultMap.put("step1OrderId", "");
				resultMap.put("keyCodeUseTime", "");
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			resultMap.put("rescode", Consts.ERROR_CODE);
			resultMap.put("resmsg", "系统错误：" + e.getMessage());
		}
		return resultMap;
	}

	/**
	 * 随机生成订单
	 * 
	 * @return
	 */
	public String createNoOrder() {
		Date now = new Date();
		SimpleDateFormat outFormat = new SimpleDateFormat("yyyyMMddHHmmss");
		String currTime = outFormat.format(now);

		String strReq = currTime;
		Random random = new Random();
		String result = "";
		for (int i = 0; i < 8; i++) {
			result += random.nextInt(10);
		}

		String requestNo = "LBAuth" + strReq + result;
		return requestNo;
	}

	@Override
	public String getSystemSettingValue(String keyName) throws Exception {
		return usersDao.getSystemSettingValue(keyName);
	}

	@Override
	public Map<String, Object> findCusAcctInfo(String id) throws Exception {
		String transCode = "E350005";
		Map<String, Object> coreMap = new HashMap<String, Object>();
		coreMap.put("userid", id);
		coreMap.put("count", "0");

		String jsonStr = CommonUtil.constructJsonStr(transCode, String.valueOf(id), coreMap);
		String rtnStr = CommonUtil.getCoreValue(jsonStr);

		JSONObject jsonObject = JSONObject.parseObject(rtnStr);
		String coreRescode = jsonObject.getString("rescode");
		if (coreRescode.equals(Consts.SUCCESS_CODE)) {
			coreMap.put("count", jsonObject.getString("count"));
		}
		return coreMap;
	}

	/**
	 * app滚动公告信息取信息system_setting
	 */
	@Override
	public NoticeInfo getSystemSettingInfo(Map<String, Object> map) {
		return usersDao.getSystemSettingInfoNew(map);
	}

	// 获取参数表信息
	public String findParamValueByName(String key) throws Exception {
		List<String> listStr = new ArrayList<String>();
		listStr.add(key);
		// 去BL查询系统参数表
		List<Map<String, Object>> extractFeeRate = this.rateRisesCouponsDao.queryParamName(listStr);
		if (extractFeeRate != null && extractFeeRate.size() > 0) {
			return (String) extractFeeRate.get(0).get("VALUE");
		}
		return null;
	}

	@Override
	public List<Map<String, String>> getSysSettByAgreementNo() throws Exception {
		// TODO Auto-generated method stub
		return usersDao.getSysSettByAgreementNo();
	}

	/***
	 * 删除微信userid绑定关系
	 * 
	 * @param userId
	 * @return
	 * @throws Exception
	 */
	@Override
	public int deleteWeixinBingding(String userId) throws Exception {
		// TODO Auto-generated method stub
		return usersDao.deleteWeixinBingding(userId);
	}

	/**
	 * 校验密码主处理
	 */
	@Override
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class, readOnly = false)
	public String checkPassword(Map<String, String> map) throws Exception {
		Map<String, Object> querMap = new HashMap<String, Object>();
		querMap.put("userMobile", map.get("phoneNum"));
		querMap.put("setupFlag", map.get("setupFlag"));

		// 从数据库中获取验证码
		String password = usersDao.queryPassword(querMap);

		if (StringUtils.isBlank(password)) {
			// 无密码的情况
			logger.error("该用户未设置登录密码");
			String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(), Consts.CHECK_CODE, "",
					"您还没有设置登录密码，请设置登录密码！");
			return result;
		}

		// 查询密码输入错误剩余次数
		int loginErrorEable = usersDao.getLoginErrorTime(map.get("phoneNum"));
		if (loginErrorEable == 0) {
			logger.error("登陆处理中已设置密码用户：" + map.get("phoneNum") + "，密码输入错误剩余次数为：" + loginErrorEable + "次");
			String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(), Consts.CHECK_CODE, "",
					"今日您已尝试输入密码超过5次");
		} else {
			if (!MD5.md5(map.get("password")).equals(password)) {
				// 修改该用户密码输入错误次数
				usersDao.updateLoginErrorTime(map.get("phoneNum"));

				logger.error("登陆处理中已设置密码用户：" + map.get("phoneNum") + "，密码输入错误剩余次数为：" + (loginErrorEable - 1) + "次");
				String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(), Consts.CHECK_CODE, "",
						"您输入的密码不正确，今日还可以尝试" + (loginErrorEable - 1) + "次");
				// "您输入的密码错误，您还有"+(loginErrorEable-1)+"次机会");
				return result;
			}
		}
		// 处理成功标志位
		map.put("dealFlag", Consts.SUCCESS_CODE);
		String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(), Consts.SUCCESS_CODE, "", "密码校验成功！");
		return result;
	}

	/**
	 * 判断用户是否存在活期订单
	 * 
	 * @throws Exception
	 */
	@Override
	public boolean isExistOrderInfo(String userId) throws Exception {
		String transCode = "E310064";
		Map<String, Object> queryCoreMap = new HashMap<String, Object>();
		queryCoreMap.put("userId", userId);
		queryCoreMap.put("planId", "109");
		String jsonStr = CommonUtil.constructJsonStr(transCode, null, queryCoreMap);
		String rtnStr = CommonUtil.getCoreValue(jsonStr);
		JSONObject jsonObject = JSONObject.parseObject(rtnStr);
		boolean existOrderId = Boolean.parseBoolean(jsonObject.getString("existOrderId"));
		return existOrderId;
	}

	/**
	 * 根据身份证号和手机号查询是否存在信息
	 */
	@Override
	public ResultDTO<String> queryUserInfoByIDCardAndMobile(JSONObject params) throws Exception {
		String phoneNo = params.getString("mobile");
		String idCard = params.getString("idCard");

		Map<String, Object> requestMap = new HashMap<String, Object>();

		requestMap.put("phoneNo", phoneNo);
		requestMap.put("idCard", idCard.toUpperCase());

		UserInfo userInfo = this.usersDao.queryUserInfoByIDCardAndMobile(requestMap);

		if (userInfo != null) {
			ResultDTO<String> resultDTO = new ResultDTO<>(ResultCode.SUCCESS, Consts.SUCCESS_DESCRIBE);
			return resultDTO;
		}
		
		
		ResultDTO<String> dto = new ResultDTO<>(ResultCode.FAILED,
				Message.CnDescriptionExpression.IDCARD_MOBILE_MATCHED);
		return dto;

	}

	/**
	 * 查询交易密码相关
	 * 
	 * @throws Exception
	 */
	@Override
	public Map<String, Object> queryPasswordCashInfo(String mobile, String passwordCash, String checkFlag)
			throws Exception {
		Map<String, Object> resultMap = new HashMap<String, Object>();

		String rescode = Consts.ERROR_CODE;
		String resmsg = "";
		String resmsg_cn = Message.CnDescriptionExpression.BUSINESSE_ERROR;

		Map<String, Object> paramsMap = new HashMap<String, Object>();
		paramsMap.put("mobile", mobile);
		resultMap.put("checkFlag", checkFlag);

		switch (Integer.parseInt(checkFlag)) {
		case 1:
			int isExistCount = usersDao.phoneIsExisted(mobile);

			if (isExistCount > 0) {

				User user = this.usersDao.getUserByParm(paramsMap);

				String passwordCashMD5 = MD5.md5(passwordCash);

				// 比较密码是否正确
				if (passwordCashMD5.equals(user.getPassword_cash())) {
					rescode = Consts.SUCCESS_CODE;
					resmsg_cn = Consts.SUCCESS_DESCRIBE;
				} else {
					resmsg_cn = Message.CnDescriptionExpression.PASSWORDCASH_ERROR;
				}

			} else {
				resmsg_cn = Message.CnDescriptionExpression.USER_NOT_EXIST;
			}

			break;
		case 2:
			User user = this.usersDao.getUserByParm(paramsMap);

			String passwordUpgrad = user.getPassword_cash();

			if ("N".equals(passwordUpgrad)) {
				resmsg_cn = Message.CnDescriptionExpression.PASSWORDCASH_NOT_UPGRADE;
			} else {
				rescode = Consts.SUCCESS_CODE;
				resmsg_cn = Consts.SUCCESS_DESCRIBE;
			}

			break;
		}

		resultMap.put("rescode", rescode);
		resultMap.put("resmsg", resmsg);
		resultMap.put("resmsg_cn", resmsg_cn);

		return resultMap;
	}

	/**
	 * 密码登陆(T_TUSER表和USER_INFO表)
	 */
	@Override
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class, readOnly = false)
	public ResultDTO dealLoginPassWord(JSONObject params) throws Exception {
		Map<String, Object> jsonMap = new HashMap<String, Object>();

		String userName = params.getString("userName");// 用户名
		String password = params.getString("password");// 密码

		String passwordMd5 = MD5.md5(password);

		List<GetUserInfo> userInfo = usersDao.loginCheck(userName, passwordMd5, "mobile");// 查询是否有这个用户

		ResultDTO result;
		if (userInfo == null || userInfo.size() <= 0) {
			logger.error("登陆处理中不存在该用户信息：" + userName);
			Map<String, Object> errorMap = errorMessageService.getErrorMessage("USERORPASSWORD_IS_INCORRECT");
			String errMsg = getErrorMsg(errorMap);
			result =new ResultDTO(ResultCode.FAILED,errMsg);
		} else if (userInfo.size() > 1) {
			logger.debug("登陆处理中用户存在多个邮箱");
			Map<String, Object> errorMap = errorMessageService.getErrorMessage("MULTIPLE_MAILBOXES_EXISTED");
			String errMsg = getErrorMsg(errorMap);
			result =new ResultDTO(ResultCode.FAILED,errMsg);
		} else {

			String dataPassword = usersDao.getUserPassword(userName);

			if (dataPassword == null || "".equalsIgnoreCase(dataPassword)) {
				logger.error("登陆处理中该用户未设置过交易密码，请用验证码登录！！！用户名：" + userName);
				Map<String, Object> errorMap = errorMessageService.getErrorMessage("EM000000017");
				String errMsg = getErrorMsg(errorMap);
				result =new ResultDTO(ResultCode.FAILED,errMsg);
			} else {
				// 查询密码输入错误剩余次数
				int loginErrorEable = usersDao.getLoginErrorTime(userName);

				if (loginErrorEable == 0) {
					logger.error("登陆处理中已设置密码用户：" + userName + "，密码输入错误剩余次数为：" + loginErrorEable + "次");
					Map<String, Object> errorMap = errorMessageService.getErrorMessage("EM000000018");
					String errMsg = getErrorMsg(errorMap);
					result =new ResultDTO(ResultCode.FAILED,errMsg);
				} else {
					if (!passwordMd5.equalsIgnoreCase(dataPassword)) {
						// 修改该用户密码输入错误次数
						usersDao.updateLoginErrorTime(userName);
						logger.error("登陆处理中已设置密码用户：" + userName + "，密码输入错误剩余次数为：" + (loginErrorEable - 1) + "次");
						String errorTime = loginErrorEable - 1 + "";
						Map<String, Object> errorMap = errorMessageService.getErrorMessage("EM000000019",
								new String[] { errorTime });
						String errMsg = getErrorMsg(errorMap);
						result =new ResultDTO(ResultCode.FAILED,errMsg);
					} else {
						logger.info("登陆处理中已设置密码用户：" + userName + "，密码校验正确");

						// 用户存在的情况下
						jsonMap.put("userId", userInfo.get(0).getId());
						jsonMap.put("userName", userName);
						if(StringUtils.isEmpty(userInfo.get(0).getPassword_cash())){
							jsonMap.put("passwordCashValidate","N");
						}else{
							jsonMap.put("passwordCashValidate","Y");
						}
						if ("Y".equals(userInfo.get(0).getIdcard_validate())
								&& "1".equals(userInfo.get(0).getIs_create_acct())) {
							jsonMap.put("identityName", userInfo.get(0).getReal_name());
							jsonMap.put("idCard", userInfo.get(0).getId_card());
							jsonMap.put("idcardValidate", "Y");
						} else {
							jsonMap.put("identityName", "");
							jsonMap.put("idCard", "");
							jsonMap.put("idcardValidate", "N");
						}

						// 查询是否绑定银行卡
						HashMap<String, Object> userPayCdParam = new HashMap<String, Object>();
						userPayCdParam.put("isValid", "Y");
						userPayCdParam.put("userId", userInfo.get(0).getId());
						userPayCdParam.put("isBinding", "Y");
						UserBankCardVo userRecePayCard = centerService.getRecePayBank(userPayCdParam);
						if (null == userRecePayCard) {
							jsonMap.put("bankCardValidate", "N");
						} else {
							jsonMap.put("bankCardValidate", "Y");
						}

						// 头像原图
						String ftpPathOriginal = userInfo.get(0).getImage_icon_original();
						// 头像缩略图
						String ftpPathDispose = userInfo.get(0).getImage_icon_dispose();
						String token = "login" + "_" + CommonUtil.getUuid();

						jsonMap.put("ftpPathOriginal", ftpPathOriginal);
						jsonMap.put("ftpPathDispose", ftpPathDispose);
						jsonMap.put("emailValidate", userInfo.get(0).getEmail_validate());
						jsonMap.put("mobileValidate", userInfo.get(0).getMobile_validate());
						jsonMap.put("email", userInfo.get(0).getEmail());
						jsonMap.put("mobile", userInfo.get(0).getMobile());
						jsonMap.put("uuid", token);

						// 登陆成功 更新最后登录时间,ip
						Map<String, String> paramsMap = new HashMap<>();
						paramsMap.put("uuid", token);
						paramsMap.put("userId", userInfo.get(0).getId() + "");
						paramsMap.put("ip", params.getString("ip"));
						// 根据用户自增ID更新用户最后登录时间
						usersDao.updateLastLoginTime(userInfo.get(0).getId() + "", params.getString("ip"));
						// uuid更新
						securityDao.updLoginTokenStr(paramsMap);

						params.put("userId", userInfo.get(0).getId() + "");

						Map<String, Object> cardReqMap = new HashMap<>();
						cardReqMap.put("userId", userInfo.get(0).getId() + "");
						// 判断用户是否进行绑卡
						List<UserRecePayCard> cardList = this.userCardDao.queryUserCardInfoByUserId(cardReqMap);

						String isBindingCard;
						if (null == cardList || cardList.size() == 0) {
							isBindingCard = "N";
						} else {
							isBindingCard = "Y";
						}

						// 恢复该用户密码输入次数超限
						usersDao.updateLoginErrorTimeBack(userName);

						jsonMap.put("isBindingCard", isBindingCard);
						jsonMap.put("yzToken", TokenUtil.genToken(jsonMap));
						result = new ResultDTO(ResultCode.SUCCESS);
						result.setRecord(jsonMap);
					}
				}
			}
		}
		return result;
	}

	/**
	 * 查询当前手机号每天只能修改五次
	 * 
	 * @return
	 * @throws Exception
	 */
	@Override
	public Map<String, String> judgeCaptchaTime(Map<String, String> map, String infoTime) throws Exception {
		// TODO Auto-generated method stub
		// 查询短信发送记录表
		Map<String, Object> querMap = new HashMap<String, Object>();
		querMap.put("userMobile", map.get("userMobile"));
		querMap.put("setupFlag", map.get("setupFlag"));
		Map sendMesRecMap = usersDao.querySendMesRec(querMap);

		Map<String, String> resultMap = new HashMap<String, String>();
		// 防止重复发送
		if (null != sendMesRecMap) {
			Date codeTime = (Date) sendMesRecMap.get("END_SETUP_TIME");// 最后发送短信时间
			Date now = usersDao.querySysDate();// 数据库当前时间
			int setupDayResult = Integer.parseInt(String.valueOf(sendMesRecMap.get("SETUP_DAY_RESULT")));// 当日发送次数

			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			// 最后发送日期
			String endSetUpDate = sdf.format(codeTime);
			// 数据库当前日期
			String dataDate = sdf.format(now);

			// 如果最后发送时间和数据库当前日期不同:恢复该用户当天发送次数
			if (!endSetUpDate.equalsIgnoreCase(dataDate)) {
				usersDao.updateJudgeCaptchaTime(querMap);

				String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(), Consts.SUCCESS_CODE, "",
						"该用户当日短信使用次数已恢复为0次");
				resultMap.put("result", result);
				resultMap.put("rescode", Consts.SUCCESS_CODE);
				return resultMap;
			} else {
				if (setupDayResult >= Integer.parseInt(infoTime)) {
					// 发短信已超过当日限额次数
					String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(), Consts.CHECK_CODE, "",
							"今日您已获取短信验证码超过" + infoTime + "次");
					resultMap.put("result", result);
					resultMap.put("rescode", Consts.CHECK_CODE);
					return resultMap;

				} else {
					// 修改该用户当日发送次数
					usersDao.addJudgeCaptchaTime(querMap);
					// 发短信已超过当日限额次数
					String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(), Consts.SUCCESS_CODE, "",
							"校验短信发送当日限额次数验证成功不超过:" + infoTime + "次" + ",当前已使用：" + setupDayResult + "次");
					resultMap.put("result", result);
					resultMap.put("rescode", Consts.SUCCESS_CODE);
					return resultMap;
				}
			}
		}
		String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(), Consts.SUCCESS_CODE, "", "");
		resultMap.put("result", result);
		resultMap.put("rescode", Consts.SUCCESS_CODE);
		return resultMap;
	}

	/**
	 * 查询任务列表
	 */
	@Override
	public JSONArray getTaskList(String userId) throws Exception {
		// TODO Auto-generated method stub
		Map<String, Object> rtnMap = new HashMap<String, Object>();
		String transCode = "E330040";
		JSONArray result = null;

		// 构建json字符串
		String jsonStr = CommonUtil.constructJsonStr(transCode, userId, new HashMap<String, Object>());

		// 调用核心接口
		String rtnStr = CommonUtil.getCoreValue(jsonStr);
		JSONObject jsonObject = JSONObject.parseObject(rtnStr);
		// rescode = "00000"
		if (Consts.SUCCESS_CODE.equals(jsonObject.getString("rescode"))) {
			JSONArray jsonArr = jsonObject.getJSONArray("list");
			if (jsonArr != null && jsonArr.size() > 0) {
				result = jsonArr;
			}
		}
		return result;
	}

	/**
	 * 查询总菜单功能定制表数据
	 */
	@Override
	public List<IcoUserFuncInfo> getAllIcoFuncList(String viewFlag) throws Exception {
//		if ("1".equals(viewFlag)) {
//			return usersDao.getAllIcoFuncListWx();
//		}
		return usersDao.getAllIcoFuncList();
	}

	/**
	 * 取得菜单功能定制表数据（更多）
	 */
	@Override
	public IcoUserFuncInfo getIcoFuncGd() throws Exception {
		// TODO Auto-generated method stub
		return usersDao.getIcoFuncGd();
	}

	/**
	 * 查询个人菜单功能定制表数据
	 */
	@Override
	public List<IcoUserFuncInfo> getUserIcoFuncList(String userId) throws Exception {
		// TODO Auto-generated method stub
		return usersDao.getUserIcoFuncList(userId);
	}

	/**
	 * 发布个人菜单功能定制表数据
	 */
	@Override
	public void addUserIcoFuncList(Map<String, String> requestMap) {
		// TODO Auto-generated method stub
		usersDao.addUserIcoFuncList(requestMap);
	}

	/**
	 * 删除个人菜单功能定制表数据
	 */
	@Override
	public void deleteUserIcoFuncSort(String userid) throws Exception {
		// TODO Auto-generated method stub
		usersDao.deleteUserIcoFuncSort(userid);
	}

	/**
	 * 通过参数查询总菜单功能定制表数据
	 * 
	 * @param userId
	 * @return
	 */
	public List<IcoUserFuncInfo> getAllIcoFuncListByParams(String userId, String viewFlag) {
		if ("1".equals(viewFlag)) {
			return usersDao.getAllIcoFuncListForwx(userId);
		}
		return usersDao.getAllIcoFuncListByParams(userId);
	}

	/**
	 * 通过参数查询总菜单功能定制表数据(老版本)
	 * 
	 * @param userId
	 * @return
	 */
	@Override
	public List<IcoUserFuncInfo> getAllIcoFuncListOld(String userId) {
		return usersDao.getAllIcoFuncListOld(userId);
	}

	/**
	 * 查询默认总菜单功能定制表数据(老版本)
	 * 
	 * @param
	 * @return
	 */
	@Override
	public List<IcoUserFuncInfo> getAllIcoFuncListDefaultOld() {
		return usersDao.getAllIcoFuncListDefaultOld();
	}

	@Override
	public String getSysSettingHtmlInfo(String name) throws Exception {
		// TODO Auto-generated method stub
		return usersDao.getSysSettingHtmlInfo(name);
	}

	/**
	 * 增加快速提现信息
	 */
	@Override
	public void insertUserQuickWithdrawInfo(String userId) throws Exception {
		// 增加快速提现信息
		UserQuickWithdraw uqw = new UserQuickWithdraw();

		String quickMonthQuickCount = findParamValueByName("quick_withdraw_count");
		String quickDaysQuickCount = findParamValueByName("quick_withdraw_days_count");
		String quickWithdrawAmount = findParamValueByName("quick_withdraw_amount");
		String quickWithdrawDmFlag = findParamValueByName("quick_withdraw_dm_flag");
		SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM");
		SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");
		uqw.setUser_id(Long.parseLong(String.valueOf(userId)));
		uqw.setMonth(sdf1.format(new Date()));
		uqw.setDays(sdf2.format(new Date()));
		uqw.setMonth_quick_count(
				StringUtils.isNotBlank(quickMonthQuickCount) ? Integer.parseInt(quickMonthQuickCount) : 0);
		uqw.setDays_quick_count(
				StringUtils.isNotBlank(quickDaysQuickCount) ? Integer.parseInt(quickDaysQuickCount) : 0);
		uqw.setWithdraw_flag(StringUtils.isNotBlank(quickWithdrawDmFlag) ? quickWithdrawDmFlag : "1");
		uqw.setQuick_withdraw_amount(
				StringUtils.isNotBlank(quickWithdrawAmount) ? new BigDecimal(quickWithdrawAmount) : BigDecimal.ZERO);
		uqw.setSystem_mouth_count(
				StringUtils.isNotBlank(quickMonthQuickCount) ? Integer.parseInt(quickMonthQuickCount) : 0);
		uqw.setSystem_days_count(
				StringUtils.isNotBlank(quickDaysQuickCount) ? Integer.parseInt(quickDaysQuickCount) : 0);

		this.userCardDao.insertUserQuickWithdrawInfo(uqw);

	}

	private String getErrorMsg(Map<String, Object> errorMap) {
		ErrorMessageSetting emsEntity = (ErrorMessageSetting) errorMap.get("errorMessage");
		String emsStr = "";
		if (null != emsEntity) {
			emsStr = emsEntity.getMessage_content();
		}
		return emsStr;
	}

	/**
	 * 上传程序方法(文件名变加密串)
	 * 
	 * @param url
	 *            FTP服务器地址
	 * @param username
	 *            FTP服务器用户名
	 * @param password
	 *            FTP服务器密码
	 * @param path
	 *            FTP服务器上传的路径
	 * @param filename
	 *            要上传的文件名称
	 * @param input
	 *            输入流
	 */
	private String uploadFile2(String url, String username, String password, String path, String filename,
			InputStream input) throws Exception {

		// 返回文件名
		String fileNameResult = "";
		// 初始表示上传失败
		boolean flag = false;
		// 创建FTPClient对象
		FTPClient ftp = new FTPClient();

		try {
			int reply;
			// 连接FTP服务器
			// 如果采用默认端口，可以使用ftp.connect(url)的方式直接连接FTP服务器
			ftp.connect(url);
			// 下面三行代码必须要，而且不能改变编码格式，否则不能正确下载中文文件
			ftp.setControlEncoding("GBK");
			FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_NT);
			conf.setServerLanguageCode("zh");
			// 登录ftp
			ftp.login(username, password);
			// 看返回的值是不是230，如果是，表示登陆成功
			reply = ftp.getReplyCode();
			// 以2开头的返回值就会为真
			if (!FTPReply.isPositiveCompletion(reply)) {
				ftp.disconnect();
				System.out.println("连接服务器失败");
			}
			System.out.println("登陆服务器成功");
			ftp.changeWorkingDirectory(path);// 转移到FTP服务器目录
			FTPFile[] fs = ftp.listFiles(); // 得到目录的相应文件列表
			// System.out.println(fs.length);
			// System.out.println("上传文件路径"+path);
			// System.out.println("上传前文件名称："+filename);
			Calendar calendar = Calendar.getInstance();
			fileNameResult = filename + ".png";

			// filenameResult =
			// String.valueOf(calendar.getTimeInMillis())
			// +filename.substring(filename.indexOf('.'),filename.length());

			// String filename1 = FtpUtil.changeName(filename, fs);
			String filename2 = new String(fileNameResult.getBytes("GBK"), "ISO-8859-1");
			String path1 = new String(path.getBytes("GBK"), "ISO-8859-1");
			// 转到指定上传目录
			ftp.changeWorkingDirectory(path1);
			// 将上传文件存储到指定目录
			// ftp.appendFile(new String(filename.getBytes("GBK"),"ISO-8859-1"),
			// input);
			ftp.setFileType(FTP.BINARY_FILE_TYPE);
			// 如果缺省该句 传输txt正常 但图片和其他格式的文件传输出现乱码
			ftp.storeFile(filename2, input);
			System.out.println("上传后文件名称：" + filename2);
			// System.out.println("上传后文件字节数："+input.available());
			// 关闭输入流
			input.close();
			// 退出ftp
			ftp.logout();
			// 表示上传成功
			flag = true;
			System.out.println("上传成功。。。。。。");
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (ftp.isConnected()) {
				try {
					ftp.disconnect();
				} catch (IOException ioe) {
				}
			}
		}
		return fileNameResult;
	}

	@Async
	public void unbindingCard(UserRecePayCard userRecePayCard, UnbindingCardApply newApply) {
		String userId = String.valueOf(newApply.getUser_id());
		Map<String, String> bankCardUnbingReqMap = new HashMap<String, String>();
		bankCardUnbingReqMap.put("userId", userId);
		Map<String, String> thridPartyResultMap = new HashMap<String, String>();
		try {
			thridPartyResultMap = ThridPartyFunctionUtil.bankCardUnbind(bankCardUnbingReqMap);
		} catch (Exception e) {
			logger.error("解绑银行卡调用第三方异常， 银行卡：" + userRecePayCard.getCard_number() + "，用户ID：" + userId, e);
			newApply.setProcessing_date(new Date());
			newApply.setProcessing_per(userId);
			newApply.setProcessing_status("2");
			userCardDao.updateUnbindingCardApply(newApply);
			return;
		}
		String rspCd = thridPartyResultMap.get("rescode");
		// 判断是否成功更新银行表信息
		if (rspCd.equals("00001")) {
			userRecePayCard.setIs_binding('N');
			userRecePayCard.setIs_valid('N');
			userRecePayCard.setLlpay_no_agree("");
			userRecePayCard.setLlpay_oid_paybill("");
			userRecePayCard.setUpdate_per(userId);
			userCardDao.updateUserBankCardInfoByIdAll(userRecePayCard);
			newApply.setProcessing_date(new Date());
			newApply.setProcessing_per(userId);
			newApply.setProcessing_status("1");
			userCardDao.updateUnbindingCardApply(newApply);
		} else {
			newApply.setProcessing_date(new Date());
			newApply.setProcessing_per(userId);
			newApply.setProcessing_status("2");
			userCardDao.updateUnbindingCardApply(newApply);
		}

	}

	/**
	 * 校验密码
	 */
	public Map<String, Object> checkLoginPWD(Map<String, String> map) throws Exception {
		String rescode = Consts.CHECK_CODE;
		String resmsg_cn = "密码不正确";
		String flag = "FALSE";
		// 从数据库中获取验证码
		String password = usersDao.getPWDByUserId(map);
		String passwordIn = map.get("password");
		if (MD5.md5(passwordIn).equals(password)) {
			rescode = Consts.SUCCESS_CODE;
			resmsg_cn = Consts.SUCCESS_DESCRIBE;
			flag = "TRUE";
		}
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("rescode", rescode);
		resultMap.put("resmsg_cn", resmsg_cn);
		resultMap.put("flag", flag);
		return resultMap;
	}

	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class, readOnly = false)
	@Override
	public Map<String, Object> authLimitValidate(Map<String, Object> map) throws Exception {
		// TODO Auto-generated method stub
		Map<String, Object> returnMap = new HashMap<String, Object>();
		String userId = (String)map.get("userId");

		// 查询用户当日实名次数是否超限
		Map<String, Object> authCountMap = new HashMap<String, Object>();
		authCountMap.put("userId", userId);
		UserAuthentication currentAuth = this.userAuthenticationDao.queryCurrentUserAuthentication(authCountMap);

		if (currentAuth != null) {
			// 从参数表获取
			Integer authLimitNumber = StringUtils.isBlank(findParamValueByName("auth_limit_number")) ? 3
					: Integer.parseInt(findParamValueByName("auth_limit_number"));
			if (currentAuth.getAuth_count() >= authLimitNumber) {
				returnMap.put("rescode", Consts.CHECK_CODE);
				returnMap.put("resmsg_cn", "当日实名次数已超限，请联系客服！");
				return returnMap;
			} else {
				// 更新表
				currentAuth.setAuth_count(currentAuth.getAuth_count() + 1);
				Integer updateCount = this.userAuthenticationDao.updateUserAuthCurrent(currentAuth);
				if (updateCount == 0) {
					returnMap.put("rescode", Consts.CHECK_CODE);
					returnMap.put("resmsg_cn", "请联系客服！");
					return returnMap;
				}
			}
		} else {
			// 插入表
			currentAuth = new UserAuthentication();
			currentAuth.setUser_id(Integer.parseInt(userId));
			currentAuth.setAuth_count(1);
			Integer insertCount = this.userAuthenticationDao.insertUserAuthCurrent(currentAuth);
			if (insertCount == 0) {
				returnMap.put("rescode", Consts.CHECK_CODE);
				returnMap.put("resmsg_cn", "请联系客服！");
				return returnMap;
			}
		}
		returnMap.put("rescode", Consts.SUCCESS_CODE);
		returnMap.put("resmsg", Consts.SUCCESS_DESCRIBE);
		return returnMap;
	}

	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class, readOnly = false)
	@Override
	public Map<String, Object> getAuthNew(Map<String, Object> map, User user,String logInfo) throws Exception {

		Map<String, Object> returnMap = new HashMap<String, Object>();
		String idCard =((String )map.get("idCard")).toUpperCase();
		String nameCard = ((String)map.get("nameCard")).replace(" ", "");
		String userId =(String) map.get("userId");
		// 更新t_User表数据

		// 生成订单号
		Map<String, String> authResult = new HashMap<String, String>();

		//移入锁-start
		// 实名认证当日次数是否超限
		Map<String, Object> authCountMap = new HashMap<String, Object>();
		authCountMap.put("userId", userId);
		UserAuthentication currentAuth = this.userAuthenticationDao.queryCurrentUserAuthentication(authCountMap);

		if (currentAuth != null) {
			// 从参数表获取
			Integer authLimitNumber = StringUtils.isBlank(findParamValueByName("auth_limit_number")) ? 3
					: Integer.parseInt(findParamValueByName("auth_limit_number"));
			if (currentAuth.getAuth_count() >= authLimitNumber) {
				logger.info(logInfo+"当日实名次数已超限，请联系客服！");
				returnMap.put("rescode", Consts.CHECK_CODE);
				returnMap.put("resmsg_cn", "当日实名次数已超限，请联系客服！");
				return returnMap;
			} else {
				// 更新表
				currentAuth.setAuth_count(currentAuth.getAuth_count() + 1);
				Integer updateCount = this.userAuthenticationDao.updateUserAuthCurrent(currentAuth);
				if (updateCount == 0) {
					logger.info(logInfo+"请联系客服！");
					returnMap.put("rescode", Consts.CHECK_CODE);
					returnMap.put("resmsg_cn", "请联系客服！");
					return returnMap;
				}
			}
		} else {
			// 插入表
			currentAuth = new UserAuthentication();
			currentAuth.setUser_id(Integer.parseInt(userId));
			currentAuth.setAuth_count(1);
			Integer insertCount = this.userAuthenticationDao.insertUserAuthCurrent(currentAuth);
			if (insertCount == 0) {
				logger.info(logInfo+"请联系客服！");
				returnMap.put("rescode", Consts.CHECK_CODE);
				returnMap.put("resmsg_cn", "请联系客服！");
				return returnMap;
			}
		}
		//移入锁-end

		// 查询ProductCode的Service名称
		Map<String, String> tprParamMap = new HashMap<String, String>();
		tprParamMap.put("productCode", "realname");
		tprParamMap.put("bankName", "-1");
		List<ThirdProductRoute> tprList = this.thirdProductRouteDao.getThirdProductRoutes(tprParamMap);

		if (tprList == null || tprList.size() == 0) {
			logger.error(logInfo+"用户《" + nameCard + "》进行实名认证，获取认证渠道列表为空。");
			returnMap.put("rescode", Consts.ERROR_CODE);
			returnMap.put("resmsg_cn", "实名认证异常，请联系客服！");
			return returnMap;
		}
		// ThirdProductRoute tpr = tprList.get(0);
		// 根据权重路由一个实名渠道
		ThirdProductRoute tpr = CommonUtil.lottery(tprList, "weight");
		if (tpr == null) {
			logger.error(logInfo+"用户《" + nameCard + "》进行实名认证，根据权重路由到的认证渠道为空。");
			returnMap.put("rescode", Consts.ERROR_CODE);
			returnMap.put("resmsg_cn", "实名认证异常，请联系客服！");
			return returnMap;
		}
		logger.info(logInfo+"用户《" + nameCard + "》进行实名认证，根据权重路由到的认证渠道是：" + tpr.getThirdPlatformName());

		Map<String, String> thirdPartyParams = new HashMap<String, String>();
		thirdPartyParams.put("productCode", tpr.getThirdProductCode());
		thirdPartyParams.put("realName", nameCard);
		thirdPartyParams.put("identityCard", idCard);

		authResult = ThirdPartyEnvUtil.invoke(logInfo, thirdPartyParams, "/route/auth");

		if (authResult == null || "sysException".equals(authResult.get("rescode"))) {
			throw new RuntimeException("实名认证失败");
		} else if ("BusinessException".equals(authResult.get("rescode"))) {
			throw new RuntimeException(String.valueOf(authResult.get("resmsg_cn")));
		}
		String rescode = authResult.get("rescode");

		// String rescode = "00"; String resmsg = "交易成功";

		if (rescode.equals("00001")) {
			String authOrderNo = authResult.get("reqOrderId");
			// String llpayOrderNo = outOrderNo;

			user.setId(Integer.parseInt(userId));
			user.setLlpay_idcard_vaildate("Y");
			user.setLlpay_order_no(authOrderNo);
			user.setLlpay_outorder_no(authOrderNo);
			user.setIdcard_validate("Y");

			this.usersDao.updateUserInfoAfterLLPayAuth(user);

			// 用户身份证认证表
			IdcardInfo idCardInfo = new IdcardInfo();

			// 更新User_info表数据
			UserInfo userInfo = this.usersDao.getUserInfo(userId);
			// 生日
			String date = IDCard.getBirthDay(idCard);
			SimpleDateFormat formatz = new SimpleDateFormat("yyyyMMdd");
			Date birthDay = formatz.parse(date);
			userInfo.setBirthday(birthDay);
			// 性别
			String sex = IDCard.getSex(idCard);
			userInfo.setGender(sex);
			userInfo.setId_card(idCard);
			userInfo.setReal_name(nameCard);
			userInfo.setUser_id(Integer.parseInt(userId));

			idCardInfo.setIdno(idCard);// 身份证
			idCardInfo.setName(nameCard);// 真实姓名
			idCardInfo.setUser_id(Integer.parseInt(userId));
			idCardInfo.setBirth(birthDay);
			// 性别
			idCardInfo.setGender(sex);

			this.usersDao.updateUserIdCardAfterLLPayAuth(userInfo);

			// 保存用户身份证认证表
			optionDao.insertIdCardInfo(idCardInfo);
			// 判断如果是铃铛用户 则只做主账户更新操作
			String utmSource = user.getUtm_source();
			if (!(utmSource.equals("92") || utmSource.equals("93"))) {
				// 判断用户是否存在主账户
				String isCreateAcct = user.getIs_create_acct();
				if (isCreateAcct.equals("1")) {
					// 根据user_id更新主账户
					String transCode = "E300055";
					Map<String, Object> coreMap = new HashMap<String, Object>();
					coreMap.put("userid", userId);
					SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");
					String sysdate = sdf.format(new Date());
					coreMap.put("sysdate", sysdate);
					coreMap.put("identitynum", idCard);
					coreMap.put("useralias", user.getNick_name());
					coreMap.put("realname", nameCard);
					coreMap.put("email", user.getEmail() == null ? "" : user.getEmail());
					coreMap.put("phoneno", user.getMobile() == null ? "" : user.getMobile());
					String jsonStr = CommonUtil.constructJsonStr(transCode, userId, coreMap);
					String rtnStr = CommonUtil.getCoreValue(jsonStr);

					JSONObject jsonObject = JSONObject.parseObject(rtnStr);
					String coreRescode = jsonObject.getString("rescode");
					if (coreRescode.equals(Consts.SUCCESS_CODE)) {
						returnMap.put("rescode", Consts.SUCCESS_CODE);
						returnMap.put("resmsg", Consts.SUCCESS_DESCRIBE);
					} else {
						returnMap.put("rescode", Consts.ERROR_CODE);
						returnMap.put("resmsg_cn", "更新主账户报错");
						throw new Exception("更新主账户报错");
					}
				} else {
					// 创建主账户
					String transCode = "E300053";
					Map<String, Object> coreMap = new HashMap<String, Object>();
					coreMap.put("userid", userId);
					SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");
					String sysdate = sdf.format(new Date());
					coreMap.put("sysdate", sysdate);
					coreMap.put("identitynum", idCard);
					coreMap.put("useralias", user.getNick_name());
					coreMap.put("realname", nameCard);
					coreMap.put("email", user.getEmail() == null ? "" : user.getEmail());
					coreMap.put("phoneno", user.getMobile() == null ? "" : user.getMobile());

					String jsonStr = CommonUtil.constructJsonStr(transCode, userId, coreMap);
					String rtnStr = CommonUtil.getCoreValue(jsonStr);

					JSONObject jsonObject = JSONObject.parseObject(rtnStr);
					String coreRescode = jsonObject.getString("rescode");
					if (coreRescode.equals(Consts.SUCCESS_CODE)) {
						// 更新用户的is_create_acct为1
						user.setIs_create_acct("1");
						this.usersDao.updateUserIsCreateAcctAfterLLPayAuth(user);

						returnMap.put("rescode", Consts.SUCCESS_CODE);
						returnMap.put("resmsg", Consts.SUCCESS_DESCRIBE);
					} else {
						returnMap.put("rescode", Consts.ERROR_CODE);
						returnMap.put("resmsg_cn", "该身份证号码已被使用!");
						throw new Exception("该身份证号码已被使用!");
					}
				}

			} else {
				// 根据user_id更新主账户
				String transCode = "E300055";
				Map<String, Object> coreMap = new HashMap<String, Object>();
				coreMap.put("userid", userId);
				SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");
				String sysdate = sdf.format(new Date());
				coreMap.put("sysdate", sysdate);
				coreMap.put("identitynum", idCard);
				coreMap.put("useralias", user.getNick_name());
				coreMap.put("realname", nameCard);
				coreMap.put("email", user.getEmail() == null ? "" : user.getEmail());
				coreMap.put("phoneno", user.getMobile() == null ? "" : user.getMobile());
				String jsonStr = CommonUtil.constructJsonStr(transCode, userId, coreMap);
				String rtnStr = CommonUtil.getCoreValue(jsonStr);

				JSONObject jsonObject = JSONObject.parseObject(rtnStr);
				String coreRescode = jsonObject.getString("rescode");
				if (coreRescode.equals(Consts.SUCCESS_CODE)) {
					returnMap.put("rescode", Consts.SUCCESS_CODE);
					returnMap.put("resmsg", Consts.SUCCESS_DESCRIBE);
				} else {
					returnMap.put("rescode", Consts.ERROR_CODE);
					returnMap.put("resmsg_cn", "更新主账户报错");
					throw new Exception("更新主账户报错!");
				}
			}

		} else {
			returnMap.put("rescode", Consts.ERROR_CODE);
			returnMap.put("resmsg_cn", "身份证号码或姓名输入有误，请确认后重新输入！");
		}
		return returnMap;
	}

	@Override
	public Map<String, Object> idCardValidate(String idCard, String idCardValidate) throws Exception {
		// TODO Auto-generated method stub
		Map<String, Object> returnMap = new HashMap<String, Object>();
		if (idCardValidate.equals("Y")) {
			returnMap.put("rescode", Consts.CHECK_CODE);
			returnMap.put("resmsg_cn", "您已实名认证成功，请勿重复实名认证！");
			return returnMap;
		}
		// 增加身份证号check判断 是否使用过该身份证号码
		Map<String, Object> idCardReqMap = new HashMap<String, Object>();
		idCardReqMap.put("identitynum", idCard);
		Integer idCardCount = this.usersDao.checkIdCardIsExist(idCardReqMap);
		if (idCardCount > 0) {
			returnMap.put("rescode", Consts.CHECK_CODE);
			returnMap.put("resmsg_cn", "该身份证号码已经被使用！");
			return returnMap;
		}
		returnMap.put("rescode", Consts.SUCCESS_CODE);
		returnMap.put("resmsg", Consts.SUCCESS_DESCRIBE);
		return returnMap;
	}

	@Override
	public User selectUser(Long id, String mobile) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("id", id);
		map.put("mobile", mobile);
		return usersDao.getUserByParm(map);
	}

	@Override
	public Date getSysdate() {
		return usersDao.getSysdate();
	}

	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class, readOnly = false)
	@Override
	public ResultDTO promptInfo(JSONObject params, RequestHeader header) throws Exception {

		// 获取参数

		final String logInfo = "promptInfo，userId=" + header.getUserId() + ",-";
		logger.info(logInfo + "开始！");
		User user = usersDao.getUserDetail(header.userId2String());
		if (null == user) {
			logger.info(logInfo + "查询不到此用户");
			return new ResultDTO(ResultCode.FAILED,"查询不到此用户");
		}

		// 查询提示信息
		UserMessage userMessage = userMessageMapper.selectByUserId(header.getUserId());
		Map<String,Object> resMap = new HashMap<>();
		if (userMessage != null) {
			// 获取域名，拼接图片地址
			String domianUrl = systemSettingDao.getSystemSettingValueByName(Consts.SystemSettingUpload.DOMAIN_NAME);
			resMap.put("isPop", "1");
			resMap.put("msgTitle", userMessage.getMessageTitle());
			resMap.put("msgContent", userMessage.getMessageContent());
			resMap.put("msgImageUrl", CommonUtil.getDomianUrl(domianUrl, userMessage.getMessageImageUrl()));
			resMap.put("appPageUrl", nvl(userMessage.getAppPageUrl()));
			resMap.put("webUrl", CommonUtil.getDomianUrl(domianUrl, userMessage.getWebUrl()));
			resMap.put("wapUrl", CommonUtil.getDomianUrl(domianUrl, userMessage.getWapUrl()));
			resMap.put("buttonName", userMessage.getButtonName());
		} else {
			resMap.put("isPop", "0");
		}

		// 更新消息为已读
		userMessageMapper.updateByUserId(header.getUserId());
		logger.info(logInfo + "结束，resMap=" + resMap);
		ResultDTO resultDTO = new ResultDTO(ResultCode.SUCCESS);
		resultDTO.setRecord(resMap);
		return resultDTO;
	}

	private Object nvl(Object obj) {
		if (obj == null) {
			return "";
		}
		return obj;
	}

	@Override
	public ResultDTO validPasswd(JSONObject params, RequestHeader header) throws Exception {
		// 获取参数
		final String logInfo = "promptInfo，userId=" + header.getUserId() + ",-";
		if (!params.containsKey("password") || StringUtils.isEmpty(params.getString("password"))) {
			logger.info(logInfo + "密码不能为空");
			return new ResultDTO(ResultCode.FAILED, "密码不能为空");
		}
		Map<String, Object> validParams = new HashMap<>();
		validParams.put("password", params.getString("password"));
		validParams.put("userId", header.getUserId());
		int i = this.userMapper.validPasswd(validParams);

		JSONObject resultJson = new JSONObject();
		if (i == 0) {
			resultJson.put("validate", "N");
			ResultDTO resultDTO = new ResultDTO(ResultCode.FAILED, "密码验证失败");
			resultDTO.setRecord(resultJson);
			return resultDTO;
		}

		resultJson.put("validate", "Y");
		ResultDTO resultDTO = new ResultDTO(ResultCode.SUCCESS, "密码验证通过");
		resultDTO.setRecord(resultJson);
		return resultDTO;
	}


	/**
	 * 查询快捷菜单项
	 * @param id
	 * @return
	 */
	@Override
	public IcoUserFuncInfo queryIcoFuncInfo(Long id)throws Exception{
		return usersDao.queryIcoFuncInfo(id);
	}

}
